Description
假设两个按元素值非递减有序排列的线性表 A 和 B,均以单链表作为存储结构,试编写程序,将 A 表和 B 表归并成一个按元素值非递增有序排列的线性表 C,并要求利用原表(即A表和B表的)结点空间存放表 C。
Input
第一行输入两个正整数 m, n(m,n<=100),用空格分开,分别表示线性表 A 和 B 中元素个数,其后两行分别输入单链表 A 和 B。
Output
输出单链表 C。
Sample
Sample Input
5 5
1 3 7 12 16
2 6 7 13 20
Sample Output
20 16 13 12 7 7 6 3 2 1
代码(有注释)
代码(去掉注释)
#include <iostream>
using namespace std;
typedef struct Node {
int data;
struct Node* next;
} Node, * LinkList;
LinkList InitList();
void InsertNode(LinkList L, int num);
int main() {
LinkList L1 = InitList();
LinkList L2 = InitList();
Node* p1, * p2;
Node* h1, * h2;
int num, count1, count2;
cin >> count1 >> count2;
while (count1--) {
cin >> num;
InsertNode(L1, num);
}
while (count2--) {
cin >> num;
InsertNode(L2, num);
}
p1 = L1->next;
p2 = L2->next;
h1 = L1;
h2 = L2;
while (p1 != NULL && p2 != NULL) {
if (p2->data >= p1->data) {
h1->next = p2;
h2->next = h2->next->next;
h1->next->next = p1;
h1 = h1->next;
p2 = h2->next;
}
else {
p1 = p1->next;
h1 = h1->next;
}
}
if (p2 != NULL) {
h1->next = p2;
}
p1 = L1->next;
while (p1 != NULL) {
cout << p1->data << " ";
p1 = p1->next;
}
}
LinkList InitList() {
LinkList L = (LinkList)malloc(sizeof(Node));
if (L == NULL) {
cout << "Error on malloc new LinkList" << endl;
exit(0);
}
L->next = NULL;
return L;
}
void InsertNode(LinkList L, int num) {
Node* p, * s;
p = L;
s = (Node*)malloc(sizeof(Node));
if (s == NULL) {
cout << "Error on malloc new Node" << endl;
exit(0);
}
s->data = num;
if (p->next == NULL) {
s->next = NULL;
p->next = s;
}
else {
s->next = p->next;
p->next = s;
}
}