-
Notifications
You must be signed in to change notification settings - Fork 0
/
7.cpp
109 lines (94 loc) · 2.26 KB
/
7.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
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode* next;
}LinkNode;
void InitLink(LinkNode*& L){
L = (LinkNode*)malloc(sizeof(LinkNode));
L->next = NULL;
}
void HeadIns(LinkNode*& L, ElemType a){
LinkNode* T;
T = (LinkNode*)malloc(sizeof(LinkNode));
T->data = a;
T->next = L->next;
L->next = T;
}
void DispLink(LinkNode* L){
while(L->next!=NULL){
cout << L->next->data << endl;
L = L->next;
}
while(true){
if(L->next==NULL){
break;
}
LinkNode* temp = L->next;
free(L);
L = temp;
}
}
LinkNode* ReverseMerge(LinkNode* L, LinkNode* M){
LinkNode* t1;
LinkNode* t2;
LinkNode* C;
InitLink(C);
while(L->next!=NULL && M->next!=NULL){
if(L->next->data < M->next->data){
t1 = L->next;
L->next = t1->next;
t1->next = C->next;
C->next = t1;
}else{
t2 = M->next;
M->next = t2->next;
t2->next = C->next;
C->next = t2;
}
}
while(L->next!=NULL){
t1 = L->next;
L->next = t1->next;
t1->next = C->next;
C->next = t1;
}
while(M->next!=NULL){
t2 = M->next;
M->next = t2->next;
t2->next = C->next;
C->next = t2;
}
free(L);
free(M);
return C;
}
int main(){
LinkNode* L;
LinkNode* M;
InitLink(L);
InitLink(M);
int num;
ElemType element;
cout << "Please enter an integer to set the array's length:" << endl;
cin >> num;
cout << "Please enter some array elements one by one in a newline:" << endl;
for (int i=0; i<num; i++){
cin >> element;
HeadIns(L, element);
}
// DispLink(L);
cout << "Please enter an integer to set the array's length:" << endl;
cin >> num;
cout << "Please enter some array elements one by one in a newline:" << endl;
for (int i=0; i<num; i++){
cin >> element;
HeadIns(M, element);
}
// DispLink(M);
cout << "The merged LinkNode:" << endl;
DispLink(ReverseMerge(L, M));
cout << "As shown, the time complexity is O(n); the space complexity if O(1)" << endl;
return 0;
}