Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e5e2754

Browse files
add LeetCode 24. 两两交换链表中的节点
1 parent 61c6e58 commit e5e2754

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
6+
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
7+
8+
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
9+
10+
11+
12+
示例:
13+
14+
```javascript
15+
给定 1->2->3->4, 你应该返回 2->1->4->3.
16+
```
17+
18+
来源:力扣(LeetCode)
19+
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
20+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
21+
22+
## 解题思路
23+
24+
**非递归解法**
25+
26+
```javascript
27+
/**
28+
* Definition for singly-linked list.
29+
* function ListNode(val) {
30+
* this.val = val;
31+
* this.next = null;
32+
* }
33+
*/
34+
/**
35+
* @param {ListNode} head
36+
* @return {ListNode}
37+
*/
38+
var swapPairs = function(head) {
39+
if(head == null || head.next == null) return head;
40+
let hummyHead = new ListNode(); // 虚拟节点
41+
hummyHead.next = head;
42+
let p = hummyHead;
43+
let node1,node2; // 当前要交换的两个节点
44+
while((node1 = p.next) && (node2 = p.next.next)){
45+
// 进行交换操作
46+
node1.next = node2.next;
47+
node2.next = node1;
48+
// 将链表串起来
49+
p.next = node2;
50+
p = node1;
51+
}
52+
return hummyHead.next;
53+
};
54+
```
55+
56+
**递归解法**
57+
58+
```javascript
59+
/**
60+
* Definition for singly-linked list.
61+
* function ListNode(val) {
62+
* this.val = val;
63+
* this.next = null;
64+
* }
65+
*/
66+
/**
67+
* @param {ListNode} head
68+
* @return {ListNode}
69+
*/
70+
var swapPairs = function (head) {
71+
if (!head || !head.next) return head;
72+
let node1 = head, node2 = head.next;
73+
node1.next = swapPairs(node2.next);
74+
node2.next = node1;
75+
return node2;
76+
};
77+
```
78+
79+
80+
## 最后
81+
文章产出不易,还望各位小伙伴们支持一波!
82+
83+
往期精选:
84+
85+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
86+
87+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
88+
89+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
90+
91+
92+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
93+
94+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
95+
96+
```javascript
97+
学如逆水行舟,不进则退
98+
```
99+
100+
101+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /