Skip to content

Commit 81c9420

Browse files
Create merge_in_between_linked_lists.cpp
1 parent 850d84a commit 81c9420

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

merge_in_between_linked_lists.cpp

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
14+
15+
16+
ListNode *l1start = list1, *l1end, *l2start = list2, *l2end;
17+
ListNode *l2begPtr, *l2endPtr;
18+
ListNode *head = list1;
19+
20+
int diff = b - a;
21+
for(int i = 0; i < a - 1; i++)
22+
l1start = l1start->next;
23+
l2begPtr = l1start;
24+
25+
26+
ListNode *tempItr = l1start->next;
27+
l1start->next = NULL;
28+
29+
cout<<l2begPtr->val<<"--"<<l1start->val<<"\n";
30+
31+
for(int i = 0; i <= diff; i++) {
32+
tempItr = tempItr->next;
33+
}
34+
l2endPtr = tempItr;
35+
36+
while(list2->next)
37+
list2 = list2->next;
38+
l2end = list2;
39+
40+
cout<<l2endPtr->val<<"--"<<l2end->val<<"\n";
41+
42+
l2begPtr->next = l2start;
43+
l2end->next = l2endPtr;
44+
45+
return head;
46+
47+
}
48+
};

0 commit comments

Comments
 (0)