-
Notifications
You must be signed in to change notification settings - Fork 0
/
ListMerge.cpp
139 lines (124 loc) · 2.47 KB
/
ListMerge.cpp
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <iostream>
#include <stdlib.h>
using namespace std;
/**
* 增序链表合并
*/
typedef struct List{
int num;
List *next;
}List;
void print(List *list){
List *t = list;
while(t != NULL){
cout <<t->num << " ";
t = t->next;
}
cout <<""<<endl;
}
void print2(List *PC){
while(PC->next){
cout <<PC->next->num<< " ";
PC = PC->next;
}
cout << "" <<endl;
}
/**
* 递归合并
*/
List *MergeList(List *list , List *list2){
if(list == NULL)
return list2;
else if(list2 == NULL)
return list;
List *temp = NULL;
if(list->num < list2->num){
temp = list;
temp->next = MergeList(list->next , list2);
}else{
temp = list2;
temp->next = MergeList(list , list2->next);
}
return temp;
}
/**
* 普通合并
*/
List *MergeList2(List *PA , List *PB , List *PC){
List *pa = PA->next;
List *pb = PB->next;
PC = PA;
List *pc = PC;
while(pa&&pb){
if(pa->num >= pb->num){
pc->next = pb;
pc = pc->next;
pb = pb->next;
}else{
pc->next = pa;
pc= pc->next;
pa = pa->next;
}
}
pc->next = pa?pa:pb;
return PC;
}
/**
* 初始化链表
*/
void InitList(List **l1 , List **l2){
(*l1) = new List;
(*l1)->next = NULL;
(*l1)->num = 0;
(*l2) = new List;
(*l2)->next = NULL;
(*l2)->num = 1;
for(int i = 10 ;i >= 2 ;i -= 2){
List *t = new List;
t->next = (*l1)->next;
(*l1)->next = t;
t->num = i;
}
for(int i = 11 ;i >= 3 ;i -= 2){
List *t = new List;
t->next = (*l2)->next;
(*l2)->next = t;
t->num = i;
}
}
/**
* 初始化带头结点链表
*/
void InitListWithHead(List **LA , List **LB){
*LA = new List;
*LB = new List;
(*LA)->next = NULL;
(*LB)->next = NULL;
for(int i = 10;i >= 0 ;i -=2){
List *t = new List;
t->num = i;
t->next = (*LA)->next;
(*LA)->next = t;
}
for(int i = 11 ;i >= 1 ;i -=2){
List *t = new List;
t->num = i;
t->next = (*LB)->next;
(*LB)->next = t;
}
}
int main(){
cout << "递归合并" <<endl;
List *l1,*l2,*l3;
InitList(&l1 , &l2);
print(l1);
print(l2);
print(MergeList(l1 ,l2));
cout << "普通合并" <<endl;
List *LA , *LB, *LC;
InitListWithHead(&LA , &LB);
print2(LA);
print2(LB);
print2(MergeList2(LA,LB,LC));
return 0;
}