首页 » 编程之美 » 正文

[leetcode_24]Swap Nodes in Pairs

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

/**
 * 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-&gt;next = tmp;<br />
        }
        return head;
    }
    bool IsCheck(ListNode * head,int PairsNum)
    {
        ListNode * now = head;
        for(int i = 0;i &lt; PairsNum;i++)
        {
            now = now-&gt;next;
            now = now-&gt;next;
        }
        if(now != NULL &amp;&amp; now-&gt;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;
    }
};

发表评论