Swap Nodes in Pairs

来源:互联网 发布:达内云笔记源码 编辑:程序博客网 时间:2024/06/04 17:42
/** * 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) {        if(!head)        {            return head;        }        ListNode *pre=head;        if(!(head->next))        {            return head;        }        ListNode *cur=head->next;        pre->next=cur->next;        cur->next=pre;        ListNode *hyperpre=pre;        head=cur;        while((hyperpre->next)&&(hyperpre->next->next))        {            pre=hyperpre->next;            cur=pre->next;            pre->next=cur->next;            cur->next=pre;            hyperpre->next=cur;            hyperpre=pre;        }        return head;    }};

0 0