给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function (head) {
const dummy = new ListNode(null, head);
let prev = dummy;
let cur = prev.next;
while (cur && cur.next) {
// 按照上图,指针更换顺序是这样子的
// prev.next = cur.next
// cur.next = prev.next.next
// prev.next.next = cur
// 也可以先用一个指针把下一个节点存起来
const next = cur.next;
cur.next = next.next;
next.next = cur;
prev.next = next;
prev = cur;
cur = cur.next;
}
return dummy.next;
};
/**
* 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) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode* dummy = new ListNode(0, head);
ListNode* prev = dummy;
ListNode* cur = prev->next;
while (cur != nullptr && cur->next != nullptr) {
ListNode* next = cur->next;
cur->next = next->next;
next->next = cur;
prev->next = next;
prev = cur;
cur = cur->next;
}
return dummy->next;
}
};
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function (head) {
// 递归出口
if (!head || !head.next) return head;
// 先保存下一个节点,避免丢失
const next = head.next;
// 下一个递归会返回互换后的第一个节点
// head 是当前组互换后的第二个节点,head.next 指向下一组就好
head.next = swapPairs(next.next);
// 将当前组的两个节点互换
next.next = head;
// 返回互换后的第一个节点
return next;
};
/**
* 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) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode* first = head;
ListNode* second = first->next;
ListNode* head_of_next_group = swapPairs(second->next);
first->next = head_of_next_group;
second->next = first;
return second;
}
};