-
Notifications
You must be signed in to change notification settings - Fork 0
/
swap_nodes_in_pairs.cpp
44 lines (42 loc) · 996 Bytes
/
swap_nodes_in_pairs.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr)
return head;
ListNode* a = head;
ListNode* b = a->next;
head = b;
ListNode* tmp = b->next;
while (a != nullptr && b != nullptr)
{
b->next = a;
if (tmp != nullptr)
{
if (tmp->next == nullptr)
{
a->next = tmp;
break;
}
else
a->next = tmp->next;
}
else
{
a->next = tmp;
break;
}
a = tmp;
b = tmp->next;
tmp = b->next;
}
return head;
}
};