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;
}
};