您的位置:首页 > Web前端 > Node.js

菜鸟刷leetcode 24. Swap Nodes in Pairs

2016-11-11 15:50 190 查看
自己写的时候,想到了交换的方法,但是没有想到前面的点没有前继,导致[1 2 3 4 5]只出现结果[1 3 5]。当时是这样写的:

while()

{

p=head->next;

head->next=p->next;

p->next=head;

head=p->next->next;

}

由于p前面没有数据,导致消失。应该加一个前继,不然链表断了。

class Solution {

public:

    ListNode* swapPairs(ListNode* head) {

        ListNode dummy(0),*pre=&dummy,*left(nullptr),*right(nullptr);

        dummy.next=head;

        while(pre!=NULL&&pre->next!=NULL&&pre->next->next!=NULL)

        {

            left=pre->next;

            right=left->next;

            left->next=right->next;

            pre->next=right;

            right->next=left;

            pre=pre->next->next;

            

            

        }

        return dummy.next;

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode