1 #include<iostream>
2 using namespace std;
3
4 typedef struct Node{
5 int data;
6 struct Node *next;
7 }Node;
8
9 //头插法建立链表
10 Node *createListFromHead(int a[], int n){
11 Node *A = new Node();
12 A->next = NULL;
13 for(int i=0; i<n; i++){
14 Node *p = new Node();
15 p->data = a[i];
16 p->next = A->next;
17 A->next = p;
18 }
19 return A;
20 }
21
22 //尾插法建立链表
23 Node *createListFromEnd(int a[], int n){
24 Node *A = new Node();
25 A->next = NULL;
26 Node *p = A;
27 for(int i=0; i<n; i++){
28 Node * q = new Node();
29 q->next = NULL;
30 q->data = a[i];
31 p->next = q;
32 p = q;
33 }
34 return A;
35 }
36
37 void show(Node *List){
38 Node *p = List->next;
39 while(p){
40 cout<<p->data<<endl;
41 p = p->next;
42 }
43 }
44
45 void uni(Node *A, Node *B){
46 Node *Apre = A, *Anow = A->next;
47 Node *Bnow = B->next;
48 while(Anow && Bnow){
49 while(Bnow && Bnow->data < Anow->data){
50 Bnow = Bnow->next;
51 }
52 if(Bnow && Bnow->data != Anow->data){
53 Apre->next = Anow->next;
54
55 }else{
56 if(!Bnow){
57 break;
58 }
59 Apre = Apre->next;
60 }
61 Anow = Anow->next;
62
63 }
64
65 Apre->next = NULL;
66 // cout<<Apre->data<<endl<<endl;
67 }
68
69 void Merge(Node *A, Node *B){
70 Node *Apre = A, *Anow = A->next;
71 Node *Bnow = B->next;
72 while(Anow && Bnow){
73 while(Anow && Anow->data < Bnow->data){
74 Anow = Anow->next;
75 Apre = Apre->next;
76 }
77 Node *Bc = Bnow;
78 Bnow = Bnow->next;
79 Bc->next = Apre->next;
80 Apre->next = Bc;
81 Apre = Apre->next;
82 }
83 Apre->next = Bnow;
84 }
85
86 int main(){
87 int a[]={1,2,4,6,8,9,11,13,17};
88 int b[]={0,3,5,6,10};
89 // Node *A = createListFromHead(a, 9);
90 Node *A = createListFromEnd(a, 9);
91 Node *B = createListFromEnd(b,5);
92 // uni(A, B);
93 Merge(A, B);
94 show(A);
95 // cout<<endl;
96 // show(B);
97 }