-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24.Swap Nodes in Pairs.js
79 lines (77 loc) · 1.45 KB
/
24.Swap Nodes in Pairs.js
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* @lc app=leetcode.cn id=24 lang=javascript
*
* [24] 两两交换链表中的节点
*
* https://leetcode-cn.com/problems/swap-nodes-in-pairs/description/
*
* algorithms
* Medium (70.77%)
* Likes: 1381
* Dislikes: 0
* Total Accepted: 440.8K
* Total Submissions: 622.3K
* Testcase Example: '[1,2,3,4]'
*
* 给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
*
*
*
* 示例 1:
*
*
* 输入:head = [1,2,3,4]
* 输出:[2,1,4,3]
*
*
* 示例 2:
*
*
* 输入:head = []
* 输出:[]
*
*
* 示例 3:
*
*
* 输入:head = [1]
* 输出:[1]
*
*
*
*
* 提示:
*
*
* 链表中节点的数目在范围 [0, 100] 内
* 0 <= Node.val <= 100
*
*
*/
// @lc code=start
/**
* 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()
dummy.next = head
let tmp = dummy, node1 = dummy, node2 = dummy
while (tmp.next && tmp.next.next) {
node1 = tmp.next
node2 = tmp.next.next
tmp.next = node2
node1.next = node2.next
node2.next = node1
tmp = node1
}
return dummy.next
};
// @lc code=end