24、 Swap Nodes in Pairs
兩兩交換鏈表中的節點
給一個鏈表,兩兩交換其中的節點,然後返回交換後的鏈表。
樣例
給出 1->2->3->4
, 你應該返回的鏈表是 2->1->4->3
。
你的算法只能使用常數的額外空間,並且不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
代碼:
/**
* 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)return NULL;
if(!head->next)return head;
ListNode *curr=head->next;
head->next=curr->next;
curr->next=head;
if(head->next)
head->next=swapPairs(head->next);
return curr;
}
};