题目描述
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
题解1(只交换值)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(! head) return head;
ListNode* dummy = head;
while(head && head->next){
int val = head->val;
head->val = head->next->val;
head = head->next;
head->val = val;
head = head->next;
}
return dummy;
}
};
题解2(典型递归)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
//终止条件
if (head == nullptr || head->next == nullptr) {
return head;
}
//一级递归任务
// 以 1->2->3为例
// 需要转成2->1->3
// 所以基础点是:
// newhead -> 2
// head -> (newhead->next) 即1 -> 3
// newhead -> head 即 2 -> 1 -> 3
ListNode* newHead = head->next;
head->next = swapPairs(newHead->next);
newHead->next = head;
return newHead;
}
};
更清晰
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(! head || ! head->next) return head;
auto one = head;
auto two = one->next;
auto three = two->next;
two->next = one;
one->next = swapPairs(three);
return two;
}
};
题解3 迭代
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(! head) return head;
ListNode* k, *dummynode, *f;
f = dummynode = new ListNode(0, head);
k = head;
while(k && k->next){
ListNode* tmp = k->next;
k->next = k->next->next;
tmp->next = k;
f->next = tmp;
f = k;
k = k->next;
}
return dummynode->next;
}
};