[leetcode_24] Swap Nodes in Pairs

这个题其实就是个模拟题,两两交换 listnode 的节点,基于 node 而非 val。蛮简单的,但是我自己确实憋了好久,一次 AC,但是感觉自己的代码写出来永远不美,复用性不高。逻辑不行。还得加油。
附上代码:

 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;
    }
};
Licensed under CC BY-NC-SA 4.0