题目
写一个算法合并两个已排序的线性表。(使用指针表示的线性表(单链表)来实现)
要求:1、定义线性表节点的结构,并定义节点的型和位置的型。
2、定义线性表的基本操作
3、在1,2的基础上,完成本题。
4、在main函数中进行测试:先构建两个有序的线性表,然后合并这两个线性表。
参考输入:
线性表A:(3,8,15,27,49)
线性表B:(6,9,13,23,57,89,97)
参考输出:
线性表C:(3,6,8,9,13,15,23,27,49,57,89,97)
实现代码
#include <iostream>
using namespace std;
typedef int ElemType;
struct celltype {
ElemType element;
celltype* next;
}; /*结点型*/
typedef celltype* LIST; /*线性表的型*/
typedef celltype* position; /*位置型*/
void Insert(ElemType x, position p, LIST& L)
{
position q = new celltype;
q->element = x;
q->next = p->next;
p->next = q;
}
position Locate(ElemType x, LIST L)
{
position p = L;
while (p->next != NULL)
if (p->next->element == x)
return p;
else
p = p->next;
return p;
}
ElemType Retrieve(position p, LIST L)
{
return p->next->element;
}
void Delete(position p, LIST& L)
{
position q;
if (p->next != NULL)
{
q = p->next;
p->next = q->next;
delete q;
}
}
position Previous(position p, LIST L)
{
position q;
if (p == L->next)
{
cout << "不存在前驱位置";
return NULL;
}
else
{
q = L;
while (q->next != p)
q = q->next;
return q;
}
}
position Next(position p, LIST L)
{
position q;
if (p->next == NULL)
{
cout << "不存在后继位置";
return NULL;
}
else
{
q = p->next;
return q;
}
}
position MakeNull(LIST& L)
{
L = new celltype;
L->next = NULL;
return L;
}
position First(LIST L)
{
return L;
}
position End(LIST L)
{
position q = L;
while (q->next != NULL)
q = q->next;
return q;
}
void Merge(LIST& LA, LIST& LB, LIST& LC)
{
position i = First(LA);
position j = First(LB);
position k = First(LC);
while ((i != End(LA)) && (j != End(LB)))
{
if (Retrieve(i, LA) <= Retrieve(j, LB))
{
Insert(Retrieve(i, LA), k, LC);
i = Next(i, LA);
k = Next(k, LC);
}
else
{
Insert(Retrieve(j, LB), k, LC);
j = Next(j, LB);
k = Next(k, LC);
}
}
while (i != End(LA))
{
Insert(Retrieve(i, LA), k, LC);
i = Next(i, LA);
k = Next(k, LC);
}
while (j != End(LB))
{
Insert(Retrieve(j, LB), k, LC);
j = Next(j, LB);
k = Next(k, LC);
}
}
int main()
{
/*LIST LA = nullptr;
MakeNull(LA);
Insert(3, End(LA), LA);
Insert(8, End(LA), LA);
Insert(15, End(LA), LA);
Insert(27, End(LA), LA);
Insert(49, End(LA), LA);
LIST LB = nullptr;
MakeNull(LB);
Insert(6, End(LB), LB);
Insert(9, End(LB), LB);
Insert(13, End(LB), LB);
Insert(23, End(LB), LB);
Insert(57, End(LB), LB);
Insert(89, End(LB), LB);
Insert(97, End(LB), LB);
LIST LC = nullptr;
MakeNull(LC);
Merge(LA, LB, LC);*/
LIST LA = nullptr;
MakeNull(LA);
cout << "请输入线性表 A 的元素数量:" << endl;
int n;
cin >> n;
cout << "请输入线性表 A 的元素:" << endl;
while (n--)
{
int x;
cin >> x;
Insert(x, End(LA), LA);
}
LIST LB = nullptr;
MakeNull(LB);
cout << "请输入线性表 B 的元素数量:" << endl;
cin >> n;
cout << "请输入线性表 B 的元素:" << endl;
while (n--)
{
int x;
cin >> x;
Insert(x, End(LB), LB);
}
LIST LC = nullptr;
MakeNull(LC);
Merge(LA, LB, LC);
cout << "线性表C:" << endl;
for (position i = First(LC); i != End(LC); i = Next(i, LC))
{
cout << Retrieve(i, LC) << ' ';
}
cout << endl;
}