力扣挑战赛第14天-No.24两两交换链表中的节点

题目描述

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

输入:head = [1,2,3,4]
输出:[2,1,4,3]

输入:head = []
输出:[]

输入:head = [1]
输出:[1]

注意:

链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100

解法一

迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 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) {
let dummyNode = new ListNode(0, head);
let cur = dummyNode;
while (cur.next && cur.next.next) {
let first = cur.next;
let second = cur.next.next;
let third = cur.next.next.next;
cur.next = second;
second.next = first;
first.next = third;
cur = cur.next.next;
}
return dummyNode.next;
};

解法二

递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 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}
*/
let swapPairs = function(head) {
if (!head || !head.next) {
return head;
}
let needSwap = head.next;
head.next = swapPairs(needSwap.next);
needSwap.next = head;
return needSwap;
};
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2020-2021 Sanmu
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信