#include <iostream>
using namespace std;
typedef int ElementType;
typedef struct Node* PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read(); /* 细节在此不表 */
void Print(List L); /* 细节在此不表;空链表将输出NULL */
List Merge(List L1, List L2);
int main()
{
List L1, L2, L;
L1 = Read();
L2 = Read();
L = Merge(L1, L2);
Print(L);
L1 = NULL;
L2 = NULL;
Print(L1);
Print(L2);
return 0;
}
List Read() {
int n;
cout << "请输入链表1结点个数" << endl;
cin >> n;
PtrToNode p = new Node;
p->Next = NULL;
PtrToNode head = p;
ElementType x;
while (n--) {
PtrToNode tem = new Node;
cin >> tem->Data;
tem->Next = NULL;
head->Next = tem;
head = head->Next;
}
head->Next = NULL;
PtrToNode t = p;
p = p->Next;
delete t;
return p;
}
List Merge(List L1, List L2) {
PtrToNode p, tem, head, t1, t2;
t1 = L1;
t2 = L2;
p = new Node;
p->Next = NULL;
head = p;
while (t1 && t2) {
if (t1->Data >= t2->Data) {
head->Next = t2; //
head = head->Next;
t2 = t2->Next;
}
else{
head->Next = t1; //
head = head->Next;
t1 = t1->Next;
}
}
head->Next = NULL;
if(t1)
head->Next = t1; //
else if (t2)
head->Next = t2; //
tem= p;
p = p->Next;
delete tem; //delete tem; p = p->Next; 卡在这卡了一个小时 如果先进行删除头指针指向
//的结点,那后面的都没了
return p;
}
void Print(List L) {
if (L== NULL)
cout << "null" << endl;
else
while (L) {
cout << L->Data << ends;
L = L->Next;
}
cout << endl;
}
合并两个链表从小到大输出(c++)
最新推荐文章于 2023-03-15 22:35:32 发布