LeetCode 23. Swap Nodes in Pairs

来源:互联网 发布:sql中查询重复的数据 编辑:程序博客网 时间:2024/06/08 03:32

用head, prev, cur三个指针维护

依题意做即可。


代码:

class Solution {public:    ListNode *swapPairs(ListNode *head)     {    ListNode *cur = head, *prev;    while(cur!=NULL && cur->next!=NULL)    {    if (cur == head)    {    auto next = cur->next->next;    head = head->next;    head->next = cur;    cur->next = next;    } else    {    auto next = cur->next->next;    prev->next = cur->next;    cur->next->next = cur;    cur->next = next;    }    prev = cur;    cur = cur->next;    }    return head;    }};


0 0