題目:https://leetcode-cn.com/explore/featured/card/recursion-i/256/principle-of-recursion/1201/
給定一個連結清單,兩兩交換其中相鄰的節點,并傳回交換後的連結清單。
你不能隻是單純的改變節點内部的值,而是需要實際的進行節點交換。
示例:
/**
* 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;
}
};