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

Swap Nodes in Pairs

2013-12-26 16:34 85 查看
Given a linked list, swap every two adjacent 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 constant space. You may not modify the values in the list, only nodes itself can be changed.

这个问题我们先建一个头结点,这样可以统一操作,每一步就那么几个操作,见图。



这样就不用特别处理第一结点,好了看明白这个图说的步骤就代码。

class Solution {
public:
ListNode *swapPairs(ListNode *head) {
if(head == NULL || head->next == NULL)
return head;
ListNode *pre, *tail;
ListNode *new_head = new ListNode(-1);
new_head->next = head;
pre = new_head;
while(pre->next && pre->next->next)
{
tail = pre->next->next;
pre->next->next = tail->next;
tail->next = pre->next;
pre->next = tail;
pre = tail->next;
}
pre = new_head;
new_head = new_head->next;
delete pre;
return new_head;
}
};


leetcode里有好多链表题,这里是创建链表的函数,想自己测试的在这里下:创建链表函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: