Skip to content

Commit 40fd08c

Browse files
committed
Merge Two Sorted Lists solution
1 parent 2fce508 commit 40fd08c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

merge-two-sorted-lists/PDKhan.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public:
3+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
4+
ListNode* new_head = NULL;
5+
ListNode* tail;
6+
7+
while(list1 || list2){
8+
ListNode* curr;
9+
10+
if(list1 && list2){
11+
if(list1->val < list2->val){
12+
curr = list1;
13+
list1 = list1->next;
14+
}else{
15+
curr = list2;
16+
list2 = list2->next;
17+
}
18+
}else if(list1){
19+
curr = list1;
20+
list1 = list1->next;
21+
}else{
22+
curr = list2;
23+
list2 = list2->next;
24+
}
25+
26+
if(new_head == NULL){
27+
new_head = curr;
28+
tail = new_head;
29+
}else{
30+
tail->next = curr;
31+
tail = tail->next;
32+
}
33+
}
34+
35+
return new_head;
36+
}
37+
};

0 commit comments

Comments
 (0)