-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmergeLinkedList.cpp
More file actions
executable file
·80 lines (62 loc) · 1.44 KB
/
mergeLinkedList.cpp
File metadata and controls
executable file
·80 lines (62 loc) · 1.44 KB
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
// Given two linked lists sorted in increasing order. Merge them such a way that the result list is in decreasing order (reverse order).
// Try solving without reverse, with O(1) auxiliary space (in-place) and only one traversal of both lists. You just need to return the head of new linked list, don't print the elements.
#include<iostream>
using namespace std;
template <typename T>
class Node {
public:
T data;
Node* next;
Node(T data) {
next = NULL;
this->data = data;
}
~Node() {
if (next != NULL) {
delete next;
}
}
};
Node<int>* merge_reverse(Node<int>* head1,Node<int>* head2) {
// Write your code here
Node<int> *temp, *p, *q, *mergedListHead;
mergedListHead = NULL;
p = head1;
q = head2;
while(p != NULL && q != NULL)
{
if(p->data < q->data)
{
temp = p;
p = p->next;
temp->next = mergedListHead;
mergedListHead = temp;
}
else
{
temp = q;
q = q->next;
temp->next = mergedListHead;
mergedListHead = temp;
}
}
while(p != NULL)
{
temp = p;
p = p->next;
temp->next = mergedListHead;
mergedListHead = temp;
}
while(q != NULL)
{
temp = q;
q = q->next;
temp->next = mergedListHead;
mergedListHead = temp;
}
return mergedListHead;
}
int main()
{
return 0;
}