-
Notifications
You must be signed in to change notification settings - Fork 258
/
Copy pathswap-two-nodes-in-linked-list.cpp
57 lines (56 loc) · 1.68 KB
/
swap-two-nodes-in-linked-list.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
// Time: O(n)
// Space: O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head a ListNode
* @oaram v1 an integer
* @param v2 an integer
* @return a new head of singly-linked list
*/
ListNode* swapNodes(ListNode* head, int v1, int v2) {
ListNode dummy{0};
dummy.next = head;
auto curr = &dummy;
ListNode *prev_node1{nullptr}, *prev_node2{nullptr};
while (curr && curr->next) {
if (curr->next->val == v1) {
prev_node1 = curr;
}
if (curr->next->val == v2) {
prev_node2 = curr;
}
if (prev_node1 && prev_node2) {
auto node1 = prev_node1->next;
auto node2 = prev_node2->next;
auto node1_next = node1->next;
auto node2_next = node2->next;
if (node1->next == node2) {
prev_node1->next = node2;
node2->next = node1;
node1->next = node2_next;
} else if (node2->next == node1) {
prev_node2->next = node1;
node1->next = node2;
node2->next = node1_next;
} else {
prev_node1->next = node2;
node2->next = node1_next;
prev_node2->next = node1;
node1->next = node2_next;
}
break;
}
curr = curr->next;
}
return dummy.next;
}
};