Skip to content

Commit 344782b

Browse files
committed
merge two sorted list and swap pairs
1 parent e8191d6 commit 344782b

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed

Merge Two Sorted Lists.cpp

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
12+
if(!l1) return l2;
13+
if(!l2) return l1;
14+
ListNode dummy(-1);
15+
ListNode *p = &dummy;
16+
for(; l1 != NULL && l2 != NULL; p = p -> next){
17+
if(l1 -> val < l2 -> val){
18+
p -> next = l1;
19+
l1 = l1 -> next;
20+
}else{
21+
p -> next = l2;
22+
l2 = l2 -> next;
23+
}
24+
}
25+
// it is possible that one of the linked list is empty
26+
// we need to check which one is NULL
27+
p -> next = l2 == NULL? l1:l2;
28+
return dummy.next;
29+
}
30+
};
31+
32+
// subtle method
33+
/**
34+
* Definition for singly-linked list.
35+
* struct ListNode {
36+
* int val;
37+
* ListNode *next;
38+
* ListNode(int x) : val(x), next(NULL) {}
39+
* };
40+
*/
41+
class Solution {
42+
public:
43+
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
44+
if(!l1) return l2;
45+
if(!l2) return l1;
46+
ListNode dummy(-1);
47+
ListNode *p = &dummy;
48+
while(l1 && l2){
49+
if(l1 -> val > l2 ->val){
50+
p ->next = l2;
51+
l2 = l2 -> next;
52+
}else{
53+
p ->next = l1;
54+
l1 = l1 -> next;
55+
}
56+
p = p -> next;
57+
}
58+
p -> next = l1 == NULL? l2:l1;
59+
return dummy.next;
60+
}
61+
};

Swap Nodes in Pairs.cpp

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
ListNode *swapPairs(ListNode *head) {
12+
if(!head) return head;
13+
ListNode dummy(-1);
14+
dummy.next = head;
15+
ListNode *p = &dummy, *q = p -> next, *k = q -> next;
16+
for(;k (the same as k != NULL); p = q, q = q -> next k = q ? q -> next : NULL){ // overflow
17+
p -> next = k;
18+
q -> next = k -> next;
19+
k -> next = q;
20+
}
21+
return dummy.next;
22+
}
23+
};
24+
// for loop definition
25+
// for( initialization; condition; increase);

0 commit comments

Comments
 (0)