leetcode系列(65)Swap Nodes in Pairs

来源:互联网 发布:长城软件怎么样 编辑:程序博客网 时间:2024/05/22 12:03

Given a linked list, swap every twoadjacent nodes and return its head.

For example,Given 1->2->3->4,you should return the list as 2->1->4->3.

Your algorithm should use only constantspace. You may not modify the values in the list, only nodesitself can be changed.

解答:这个题目唯一增加的难度就是不准交互value,必须操作节点,用dummy_node的方式在操作链表的时候非常用,且会减少代码的难度。

class Solution {public:    ListNode* swapPairs(ListNode* head) {        ListNode dummy(0);        dummy.next = head;        ListNode* pre = &dummy;        ListNode* cur = head;        while (cur != nullptr && cur->next != nullptr) {            ListNode* nxt = cur->next;            cur->next = nxt->next;            nxt->next = cur;            pre->next = nxt;            // update cur and pre            pre = cur;            cur = cur->next;        }        return dummy.next;    }};


0 0