-
Notifications
You must be signed in to change notification settings - Fork 0
/
60.LinkedList_merging.cpp
88 lines (81 loc) · 1.64 KB
/
60.LinkedList_merging.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
#include<iostream>
using namespace std;
struct node{
int data;
node* next;
};
node* create(int A[], int num){
node* first = new node;
first->data = A[0];
node *temp,*last;
last = first;
for(int i=1;i<num;i++){
temp = new node;
temp->data = A[i];
temp->next = NULL;
last->next = temp;
last = temp;
}
return first;
}
node* merge(node* p, node* q){
node* head=NULL;
node* tail=NULL;
while(p && q){
if(p->data <= q->data){
if(head==NULL){
head=tail=p;
p=p->next;
} else{
tail->next=p;
tail=p;
p=p->next;
tail->next=NULL;
}
}
else{
if(head==NULL){
head=tail=q;
q=q->next;
} else{
tail->next=q;
tail=q;
q=q->next;
tail->next=NULL;
}
}
}
while(p){
tail->next = p;
tail = p;
p = p->next;
tail->next = NULL;
}
while(q){
tail->next = q;
tail = q;
q = q->next;
tail->next = NULL;
}
return head;
}
void display(node* p){
while(p){
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
int main(){
int a[] = {1,5,8,11};
int b[] = {2,3,5,9};
node* first = create(a,4);
cout<<"first: ";
display(first);
node* second = create(b,4);
cout<<"second: ";
display(second);
node* merged = merge(first,second);
cout<<"merged: ";
display(merged);
}