This problem is essentially a simulation problem — swap ListNode nodes in pairs, based on nodes rather than values. It’s fairly simple, but I struggled with it for quite a while. Got AC on the first try, but I feel like my code never looks elegant and lacks reusability. My logic needs improvement. Still need to keep working hard.
Here is the code:
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
| /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *swapPairsStep(ListNode *head, int PairsNum) {
ListNode *now = head;
ListNode *before;
for (int i = 0; i < PairsNum; i++) {
now = now->next;
before = now;
now = now->next;
}
if (PairsNum == 0) {
ListNode *tmp = now->next;
now->next = now->next->next;
tmp->next = now;
return tmp;
} else {
ListNode *tmp = now->next;
now->next = now->next->next;
tmp->next = now;
before->next = tmp;
}
return head;
}
bool IsCheck(ListNode *head, int PairsNum) {
ListNode *now = head;
for (int i = 0; i < PairsNum; i++) {
now = now->next;
now = now->next;
}
if (now != NULL && now->next != NULL) {
return true;
} else {
return false;
}
}
ListNode *swapPairs(ListNode *head) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int num = 0;
while (IsCheck(head, num)) {
head = swapPairsStep(head, num);
num++;
}
return head;
}
};
|