题目描述
假定两个单链表是递增有序,定义并实现以下函数,完成两个单链表的合并,继续保持递增有序
int LL_merge(ListNode *La, ListNode *Lb)
输入
第1行先输入n表示有n个数据,接着输入n个数据
第2行先输入m表示有M个数据,接着输入m个数据
输出
输出合并后的单链表数据,数据之间用空格隔开
输入样例:
3 11 33 55
4 22 44 66 88
输出样例:
11 22 33 44 55 66 88
#include <iostream>
using namespace std;
#define ok 0
#define error -1
class ListNode
{
public:
int data;
ListNode* next;
ListNode()
{
next = NULL;
}
};
class Linklist
{
public:
ListNode* head;
int len;
Linklist()
{
head = new ListNode();
len = 0;
}
void LL_intsert(int i, int item)
{
ListNode* p = head;
ListNode* s = new ListNode();
int j = 0;
while (p && j < i - 1)
{
p = p->next;
j++;
}
if (!p || j > i - 1)
return;
s->data = item;
s->next = p->next;
p->next = s;
len++;
}
int LL_merge(ListNode* La, ListNode* Lb) //递增的顺序合并
{
Linklist L3;
ListNode* p = La->next, * q = Lb->next,*Lc;
Lc = L3.head = La;//L3链表的头结点是La
while (p && q) //只要一个为空就会退出循环
{
if (p->data <= q->data)
{
Lc->next = p;
Lc = p;
p = p->next;
}
else
{
Lc->next = q;
Lc = q;
q = q->next;
}
}
Lc->next = p ? p : q; //补上还未遇到空的剩下的链表
delete(Lb);
L3.LL_display();
return ok;
}
void LL_display()
{
ListNode* p;
p = head->next;
while (p)
{
cout << p->data << " ";;
p = p->next;
}
cout << endl;
}
};
int main()
{
int n, m, item, x;
Linklist L1,L2;
ListNode* La = L1.head;
ListNode* Lb = L2.head;
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> item;
L1.LL_intsert(i, item);
}
cin >> m;
for (int i = 1; i <= m; i++)
{
cin >> item;
L2.LL_intsert(i, item);
}
x = L1.LL_merge(La, Lb);
return 0;
}