代码改变世界

leetcode24. Swap Nodes in Pairs

2018-09-24 16:33  legend聪  阅读(161)  评论(0编辑  收藏  举报

创建指针pre来指向交换结点的前一个结点,然后按照指针含义每次移动pre。

/**
* 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) {
        ListNode* dummyNode;
        dummyNode = new ListNode(0);
        dummyNode->next = head;
        ListNode* pre;//指向交换元素的前一个元素
        ListNode* node1;// 指向两个待交换的元素
        ListNode* node2;
        ListNode* next;
        pre = dummyNode;
        while (pre->next != NULL&&pre->next->next != NULL)
        {
            node1 = pre->next;
            node2 = node1->next;
            next = node2->next;
            node2->next = node1;
            node1->next = next;
            pre->next = node2;
            pre = node1;
        }
        ListNode* res;
        res = dummyNode->next;
        delete dummyNode;
        return res;
    }
};