您的位置:首页 > 理论基础 > 数据结构算法

C#实现数据结构(二)

2009-08-01 09:30 197 查看
例:有数据类型为整形的顺序表s1和s2,其数据元素均按从小到大排列的,编写一个算法将它们合并为一个表lc,要求lc中的元素也是按从小到大的。

从上篇得到了一个顺序表的描述与实现,所以顺序表的实现在此不再列出

以下,是上述算法的实现:

class Program

{

static void Main(string[] args)

{

SeqList<int> ss=new SeqList<int>(5);

for (int i = 0; i < 5; i++)

{

ss.Append(i);

}

SeqList<int> ss2 = new SeqList<int>(7);

for (int i = 0; i < 7; i++)

{

ss2.Append(i + 2);

}

SeqList<int> ww = LinkC(ss, ss2);

//取长度

Console.WriteLine(ww.GetLength());

for (int i = 0; i <= ww.Last; i++)

{

Console.WriteLine(ww.GetElem(i+1).ToString());

}

}

public static SeqList<int> LinkC(SeqList<int> s1, SeqList<int> s2)

{

SeqList<int> lc = new SeqList<int>(s1.Maxsize + s2.Maxsize);

int i = 0;

int j = 0;

while ((i <= s1.GetLength() - 1) && (j <= s2.GetLength() - 1))

{

if (s1[i] < s2[j])

{

lc.Append(s1[i++]);

}

else

{

lc.Append(s2[j++]);

}

}

//如果s1中还有数据

while (i <= s1.GetLength() - 1)

{

lc.Append(s1[i++]);

}

//如果s2中还有数据

while (j <= s2.GetLength() - 1)

{

lc.Append(s2[j++]);

}

return lc;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: