c/c++:有序链表的归并

数据结构实验之链表四:有序链表的归并

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>
#include <cstring>
using namespace std;
struct node
{
int data;
struct node *next;
};


int main ()
{
std::ios::sync_with_stdio(false);

int length1,length2;
struct node *head1,*head2,*tail1,*tail2,*p1,*p2,*tmp;

head1 = new node;
tail1 = head1;
head1->next = NULL;

head2 = new node ;
tail2 = head2;
head2->next = NULL;


cin >>length1>>length2;

while(length1 -- )
{
p1 = new node ;
cin>>p1->data;
tail1->next = p1;
tail1 = p1;
}
p1->next = NULL;

while(length2 -- )
{
p2 = new node ;
cin>>p2->data;
tail2->next = p2;
tail2 = p2;
}
p2->next = NULL;

p1 = head1;
p2 = head2;


struct node *head,*tail;

head = new node;
head->next = NULL;
tail = head;

p1 = head1->next;
p2 = head2->next;


while(p1&&p2){
if(p1->data < p2->data){
tail->next = p1;
p1 = p1->next;
} else {
tail->next = p2;
p2 = p2->next;
}
tail = tail->next;
}


if(p1){
tail->next = p1;
} else {
tail->next = p2;
}

delete(head2);
delete(head1);

p1 = head->next;
while(p1->next!=NULL){
cout<<p1->data<<' ';
p1 = p1->next;
}

cout << p1->data<<endl;

return 0;
}