File tree 2 files changed +85
-0
lines changed
2 files changed +85
-0
lines changed Original file line number Diff line number Diff line change 24
24
* [ 21. Merge Two Sorted Lists] ( leetCode-21-Merge-Two-Sorted-Lists.md )
25
25
* [ 22. Generate Parentheses] ( leetCode-22-Generate-Parentheses.md ) Merge k Sorted Lists
26
26
* [ 23. Merge k Sorted Lists] ( leetCode-23-Merge-k-Sorted-Lists.md )
27
+ * [ 24. Swap Nodes in Pairs] ( leetCode-24-Swap-Nodes-in-Pairs.md )
27
28
* [ 79. Word Search] ( leetCode-79-Word-Search.md )
Original file line number Diff line number Diff line change
1
+ # 题目描述(中等难度)
2
+
3
+ ![ ] ( https://windliang.oss-cn-beijing.aliyuncs.com/24.jpg )
4
+
5
+
6
+
7
+ 给定一个链表,然后两两交换链表的位置。
8
+
9
+ # 解法一 迭代
10
+
11
+ 首先为了避免单独讨论头结点的情况,一般先申请一个空结点指向头结点,然后再用一个指针来遍历整个链表。
12
+
13
+ 先来看一下图示:
14
+
15
+ ![ ] ( https://windliang.oss-cn-beijing.aliyuncs.com/24_2.jpg )
16
+
17
+ ![ ] ( https://windliang.oss-cn-beijing.aliyuncs.com/24_3.jpg )
18
+
19
+
20
+
21
+ ![ ] ( https://windliang.oss-cn-beijing.aliyuncs.com/24_4.jpg )
22
+
23
+
24
+
25
+ ![ ] ( https://windliang.oss-cn-beijing.aliyuncs.com/24_5.jpg )
26
+
27
+ ![ ] ( https://windliang.oss-cn-beijing.aliyuncs.com/24_6.jpg )
28
+
29
+ point 是两个要交换结点前边的一个位置。
30
+
31
+ ``` java
32
+ public ListNode swapPairs(ListNode head) {
33
+ ListNode dummy = new ListNode (0 );
34
+ dummy. next = head;
35
+ ListNode point = dummy;
36
+ while (point. next != null && point. next. next != null ) {
37
+ ListNode swap1 = point. next;
38
+ ListNode swap2 = point. next. next;
39
+ point. next = swap2;
40
+ swap1. next = swap2. next;
41
+ swap2. next = swap1;
42
+ point = swap1;
43
+ }
44
+ return dummy. next;
45
+ }
46
+ ```
47
+
48
+ 时间复杂度:O(n)。
49
+
50
+ 空间复杂度:O(1)。
51
+
52
+ # 解法二 递归
53
+
54
+ 参考[ 这里] ( https://leetcode.com/problems/swap-nodes-in-pairs/discuss/11030/My-accepted-java-code.-used-recursion. ) 。
55
+
56
+ 自己画了个参考图。
57
+
58
+ ![ ] ( https://windliang.oss-cn-beijing.aliyuncs.com/24_7.jpg )
59
+
60
+ ![ ] ( https://windliang.oss-cn-beijing.aliyuncs.com/24_8.jpg )
61
+
62
+ ``` java
63
+ public ListNode swapPairs(ListNode head) {
64
+ if ((head == null )|| (head. next == null ))
65
+ return head;
66
+ ListNode n = head. next;
67
+ head. next = swapPairs(head. next. next);
68
+ n. next = head;
69
+ return n;
70
+ }
71
+ ```
72
+
73
+ 递归时间复杂度留坑。
74
+
75
+ # 总
76
+
77
+ 自己开始没有想出递归的算法,每次都会被递归的简洁吸引。另外,感觉链表的一些题,只要画图打打草稿,搞清指向关系,一般不难。
78
+
79
+
80
+
81
+
82
+
83
+
84
+
You can’t perform that action at this time.
0 commit comments