給定一個(gè)鏈表,調(diào)換每?jī)蓚€(gè)相鄰節(jié)點(diǎn),并返回其頭部。
例如,
給定 1->2->3->4, 你應(yīng)該返回的鏈表是 2->1->4->3。
你的算法必須使用唯一不變的空間。
你也不能修改列表中的值,只有節(jié)點(diǎn)本身是可以改變的。
Give 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.
我們就以題目中給出的 1,2,3,4 作為示例,將其作為兩部分
1,2 -- 3,4
或者我畫(huà)個(gè)圖出來(lái)更加直觀吧……
http://wiki.jikexueyuan.com/project/leetcode-book/images/7.png" alt="" />
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode* next;
* ListNode(int x): val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL) return NULL;
if(head->next == NULL) return head;
ListNode* temp = head->next;
head->next = swapPairs(temp->next);
temp->next = head;
return temp;
}
};