-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_two_linked_list_alternative.cpp
112 lines (94 loc) · 2.38 KB
/
merge_two_linked_list_alternative.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
//Merge two linked lists
//https://ide.geeksforgeeks.org/XEdZQrsmGH
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node* next;
};
struct Node* head;
//createNode
struct Node* createNode(int data){
struct Node* tmp = new Node;
tmp->data = data;
tmp->next = NULL;
return tmp;
}
//printLL
void printLL(struct Node* head){
if(head == NULL) return;
while(head != NULL){
cout<<head->data<<" ";
head = head->next;
}
cout<<"\n";
}
struct Node* mergeLL1(struct Node* A, struct Node* B){
struct Node* head;
if(A == NULL && B == NULL) return NULL;
if(A == NULL) return B;
else if(B == NULL) return A;
else{
//set the head
if(A->data <= B->data){
head = A; A = A->next;
}
else{
head = B; B = B->next;
}
struct Node* curr = head; //now we have head set lets loop in
while((A != NULL) || (B != NULL)){
if(A == NULL){
curr->next = B;
return head;
}
else if(B == NULL){
curr->next = A;
return head;
}
else{
if(A->data <= B->data){
curr->next = A;
curr = curr->next;
A = A->next;
}
else{
curr->next = B;
curr = curr->next;
B = B->next;
}
}
}
curr->next = NULL;
return head;
}
}
struct Node* mergeLL(struct Node* A, struct Node* B){
struct Node* dummy = createNode(0);
struct Node* temp = dummy;
while(A && B){
if(A->data <= B->data){
temp->next = A;
temp = temp->next;
A = A->next;
}
else{
temp->next = B;
temp = temp->next;
B = B->next;
}
}
if(!A) temp->next = B;
if(!B) temp->next = A;
return dummy->next;
}
int main(){
struct Node* head1 = createNode(2);
head1->next = createNode(4);
head1->next->next = createNode(6);
struct Node *head2 = createNode(1);
head2->next = createNode(3);
head2->next->next = createNode(5);
struct Node* head = mergeLL1(head1, head2);
printLL(head);
}