題目:https://leetcode-cn.com/explore/featured/card/recursion-i/256/principle-of-recursion/1201/
給定一個鏈表,兩兩交換其中相鄰的節點,並返回交換後的鏈表。
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
示例:
給定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 == NULL|| head->next==NULL) return head;
ListNode* p = head->next;
ListNode* temp = p->next;
p->next = head;
head->next = swapPairs(temp);
return p;
}
};