#451 Swap Nodes in Pairs

来源:互联网 发布:js 指定时间转时间戳 编辑:程序博客网 时间:2024/06/07 13:23

题目描述:

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

Example

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

Challenge 

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

题目思路:

这题继续用好用的dummy head,然后就是指针swap,需要注意的是swap过程中的顺序。

Mycode(AC = 31ms):

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    /**     * @param head a ListNode     * @return a ListNode     */    ListNode* swapPairs(ListNode* head) {        // Write your code here        ListNode *dummy = new ListNode(0);        dummy->next = head;                ListNode *tmp = dummy, *next = dummy->next;        while (next && next->next) {            tmp->next = next->next;            next->next = tmp->next->next;            tmp->next->next = next;                        tmp = next;            next = tmp->next;        }                return dummy->next;    }};


0 0
原创粉丝点击