-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSwapNodesInPairs.java
More file actions
101 lines (91 loc) · 2.61 KB
/
Copy pathSwapNodesInPairs.java
File metadata and controls
101 lines (91 loc) · 2.61 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
* <p>给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。</p>
*
* <p> </p>
*
* <p><strong>示例 1:</strong></p>
* <img alt="" src="https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg" style="width: 422px; height: 222px;" />
* <pre>
* <strong>输入:</strong>head = [1,2,3,4]
* <strong>输出:</strong>[2,1,4,3]
* </pre>
*
* <p><strong>示例 2:</strong></p>
*
* <pre>
* <strong>输入:</strong>head = []
* <strong>输出:</strong>[]
* </pre>
*
* <p><strong>示例 3:</strong></p>
*
* <pre>
* <strong>输入:</strong>head = [1]
* <strong>输出:</strong>[1]
* </pre>
*
* <p> </p>
*
* <p><strong>提示:</strong></p>
*
* <ul>
* <li>链表中节点的数目在范围 <code>[0, 100]</code> 内</li>
* <li><code>0 <= Node.val <= 100</code></li>
* </ul>
* <div><div>Related Topics</div><div><li>递归</li><li>链表</li></div></div><br><div><li>👍 1194</li><li>👎 0</li></div>
*/
package leetcode1;
public class SwapNodesInPairs {
public static void main(String[] args) {
Solution solution = new SwapNodesInPairs().new Solution();
}
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
/**
* 四指针法,非递归
* 注:node节点交换后,再使用节点时注意使用已交换的节点,此处不要被坑了
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode prev = new ListNode();
prev.next = head;
head = prev;
while (prev.next != null && prev.next.next != null) {
ListNode a = prev.next;
ListNode b = a.next;
ListNode next = b.next;
prev.next = b;
b.next = a;
a.next = next;
// 下面这行代码极其容易写错
prev = a;
}
return head.next;
}
}
/**
* 递归
*/
class Solution2 {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
}
}