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

#451 Swap Nodes in Pairs

2016-08-12 11:48 295 查看
题目描述:

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

Have you met this question in a real interview? 

Yes

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode linked list