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;
}
}
从上篇得到了一个顺序表的描述与实现,所以顺序表的实现在此不再列出
以下,是上述算法的实现:
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;
}
}
相关文章推荐
- C# 数据结构基础-实现循环队列
- 数据结构与算法(C#实现)系列---二叉树
- 常用数据结构及算法C#/Java实现
- 数据结构之应用 "栈(Stack)" 实现: 解析算术表达式及计算求值 (C#/Java)
- 数据结构课程设计-----用C#实现双向链表
- 数据结构之排序算法--C#实现
- C# 数据结构基础-实现循环队列
- C#使用Jquery zTree实现树状结构显示 异步数据加载
- 数据结构课程设计-----用C#实现双向链表
- 数据结构之应用 "栈(Stack)" 实现: 解析算术表达式及计算求值 (C#/Java)
- 数据结构与算法(C#实现)系列---AVLTree(二)(外摘)
- 数据结构与算法(C#实现)系列---二叉树
- C#中Merge方法实现把不同表结构的表合并成一张表,同时合并数据
- 数据结构与算法---C#实现LinkedList实例
- 数据结构与算法(C#实现)系列---演示篇(一)(外摘)
- 数据结构(C#)--递归和动态规划法实现斐波那契数列的方法
- C#实现二叉树数据结构以及先序、中序、后续遍历
- 数据结构之应用 "栈(Stack)" 实现: 解析算术表达式及计算求值 (C#/Java)
- C#使用Jquery zTree实现树状结构显示_异步数据加载
- 【数据结构与算法】c# Dictionary内部实现