@@ -13,11 +13,11 @@ Example:
13
13
Given 1->2->3->4, you should return the list as 2->1->4->3.
14
14
## 思路
15
15
16
- 设置一个dummy 节点简化操作, dummy next 指向head 。
16
+ 设置一个 dummy 节点简化操作, dummy next 指向 head 。
17
17
18
- 1 . 初始化first为第一个节点
19
- 2 . 初始化second为第二个节点
20
- 3 . 初始化current为dummy
18
+ 1 . 初始化 first 为第一个节点
19
+ 2 . 初始化 second 为第二个节点
20
+ 3 . 初始化 current 为 dummy
21
21
4 . first.next = second.next
22
22
5 . second.next = first
23
23
6 . current.next = second
@@ -26,45 +26,19 @@ Given 1->2->3->4, you should return the list as 2->1->4->3.
26
26
27
27
![ 24.swap-nodes-in-pairs] ( ../assets/24.swap-nodes-in-pairs.gif )
28
28
29
- ( 图片来自: https://github.com/MisterBooo/LeetCodeAnimation )
29
+ ( 图片来自: https://github.com/MisterBooo/LeetCodeAnimation )
30
30
31
31
## 关键点解析
32
32
33
33
1 . 链表这种数据结构的特点和使用
34
34
35
- 2 . dummyHead简化操作
35
+ 2 . dummyHead 简化操作
36
36
37
37
## 代码
38
38
39
39
* 语言支持:JS,Python3
40
40
41
41
``` js
42
- /*
43
- * @lc app=leetcode id=24 lang=javascript
44
- *
45
- * [24] Swap Nodes in Pairs
46
- *
47
- * https://leetcode.com/problems/swap-nodes-in-pairs/description/
48
- *
49
- * algorithms
50
- * Medium (43.33%)
51
- * Total Accepted: 287.2K
52
- * Total Submissions: 661.3K
53
- * Testcase Example: '[1,2,3,4]'
54
- *
55
- * Given a linked list, swap every two adjacent nodes and return its head.
56
- *
57
- * You may not modify the values in the list's nodes, only nodes itself may be
58
- * changed.
59
- *
60
- *
61
- *
62
- * Example:
63
- *
64
- *
65
- * Given 1->2->3->4, you should return the list as 2->1->4->3.
66
- *
67
- */
68
42
/**
69
43
* Definition for singly-linked list.
70
44
* function ListNode(val) {
@@ -85,7 +59,7 @@ var swapPairs = function(head) {
85
59
const first = current .next ;
86
60
const second = current .next .next ;
87
61
88
- // 更新双指针和current指针
62
+ // 更新双指针和 current 指针
89
63
first .next = second .next ;
90
64
second .next = first;
91
65
current .next = second;
@@ -103,13 +77,13 @@ class Solution:
103
77
def swapPairs (self , head : ListNode) -> ListNode:
104
78
"""
105
79
用递归实现链表相邻互换:
106
- 第一个节点的next是第三 、第四个节点交换的结果,第二个节点的next是第一个节点 ;
107
- 第三个节点的next是第五 、第六个节点交换的结果,第四个节点的next是第三个节点 ;
80
+ 第一个节点的 next 是第三 、第四个节点交换的结果,第二个节点的 next 是第一个节点 ;
81
+ 第三个节点的 next 是第五 、第六个节点交换的结果,第四个节点的 next 是第三个节点 ;
108
82
以此类推
109
83
:param ListNode head
110
84
:return ListNode
111
85
"""
112
- # 如果为None或next为None ,则直接返回
86
+ # 如果为 None 或 next 为 None ,则直接返回
113
87
if not head or not head.next:
114
88
return head
115
89
0 commit comments