-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1669. Merge In Between Linked Lists.cpp
94 lines (83 loc) · 2.06 KB
/
1669. Merge In Between Linked Lists.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
// Iterative
// Time complexity - O(N)
// Space complexity- O(1)
class Solution {
public:
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
//finding the first and last node
ListNode* nodeF=list2;
ListNode* nodeL=NULL;
while(list2)
{
nodeL=list2;
list2=list2->next;
}
//deletion and insertion
ListNode* head=list1;
ListNode* node1=NULL;
ListNode* node2=NULL;
int pos=0;
while(head)
{
if(pos==a-1)
node1=head;
else if(pos==b+1)
{
node2=head;
break;
}
head=head->next;
pos++;
}
node1->next=nodeF;
nodeL->next=node2;
return list1;
}
};
// Recursion
// Time complexity - O(N)
// Space complexity- O(N)
class Solution {
public:
ListNode* help(ListNode* list1,int pos,int a,int b,ListNode* nodeF,ListNode* nodeL)
{
//base case
if(!list1)
return NULL;
//recursive calls
//and small calculation
ListNode* temp=help(list1->next,pos+1,a,b,nodeF,nodeL);
if(pos>a and pos<b)
{
delete list1;
return temp;
}
if(pos==a and pos==b)
{
nodeL->next=temp;
return nodeF;
}
else if(pos==a)
return nodeF;
else if(pos==b)
{
nodeL->next=temp;
delete list1;
return nodeL;
}
list1->next=temp;
return list1;
}
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
//finding the first and last node
ListNode* nodeF=list2;
ListNode* nodeL=NULL;
while(list2)
{
nodeL=list2;
list2=list2->next;
}
//inserting list2 in between list1
return help(list1,0,a,b,nodeF,nodeL);
}
};