File tree Expand file tree Collapse file tree 1 file changed +104
-0
lines changed
zh-tw/basics_data_structure Expand file tree Collapse file tree 1 file changed +104
-0
lines changed Original file line number Diff line number Diff line change 8
8
9
9
鏈表就是鏈式儲存的線性表。根據指標域的不同,鏈表分為單向鏈表、雙向鏈表、循環鏈表等等。
10
10
11
+ ## 程式碼實現
12
+
13
+ ### Python
14
+
15
+ ``` python
16
+ class ListNode :
17
+ def __init__ (self , val ):
18
+ self .val = val
19
+ self .next = None
20
+ ```
21
+
22
+ ###C++
23
+ ``` cpp
24
+ struct ListNode {
25
+ int val;
26
+ ListNode * next;
27
+ ListNode(int val, ListNode * next=NULL): val (val),next(next){}
28
+ };
29
+
30
+ ```
31
+
32
+ ### Java
33
+
34
+ ```java
35
+ public class ListNode {
36
+ public int val;
37
+ public ListNode next;
38
+ public ListNode(int val) {
39
+ this.val = val;
40
+ this.next = null;
41
+ }
42
+ }
43
+ ```
44
+
11
45
## 鏈表的基本操作
12
46
13
47
### 反轉單向鏈表(singly linked list)
@@ -29,6 +63,52 @@ public ListNode reverse(ListNode head) {
29
63
}
30
64
```
31
65
66
+ #### 雙向鏈表
67
+
68
+ 和單向鏈表的區別在於:雙向鏈表的反轉核心在於` next ` 和` prev ` 域的交換,還需要注意的是目前節點和上一個節點的遞推。
69
+
70
+ ### Python
71
+
72
+ ``` python
73
+ class DListNode :
74
+ def __init__ (self , val ):
75
+ self .val = val
76
+ self .prev = self .next = null
77
+
78
+ def reverse (self , head ):
79
+ curt = None
80
+ while head:
81
+ curt = head
82
+ head = curt.next
83
+ curt.next = curt.prev
84
+ curt.prev = head
85
+ return curt
86
+ ```
87
+
88
+ ### Java
89
+
90
+ ``` java
91
+ class DListNode {
92
+ int val;
93
+ DListNode prev, next;
94
+ DListNode (int val ) {
95
+ this . val = val;
96
+ this . prev = this . next = null ;
97
+ }
98
+ }
99
+
100
+ public DListNode reverse(DListNode head) {
101
+ DListNode curr = null ;
102
+ while (head != null ) {
103
+ curr = head;
104
+ head = curr. next;
105
+ curr. next = curr. prev;
106
+ curr. prev = head;
107
+ }
108
+ return curr;
109
+ }
110
+ ```
111
+
32
112
### 刪除鏈表中的某個節點
33
113
34
114
刪除鏈表中的某個節點一定需要知道這個點的前繼節點,所以需要一直有指標指向前繼節點。
@@ -57,3 +137,27 @@ Dummy node 是一個虛擬節點,也可以認為是標竿節點。Dummy node
57
137
- 判斷單向鏈表是否有環
58
138
利用快慢指標的原理,同樣設置兩個指標 `*fast`、`*slow` 都指向單向鏈表的頭節點,其中 `*fast`的移動速度是`*slow`的2倍。如果 `*fast = NULL`,說明該單向鏈表 以 `NULL`結尾,不是循環鏈表;如果 `*fast = *slow`,則快指標追上慢指標,說明該鏈表是循環鏈表。
59
139
140
+
141
+ ### Python
142
+
143
+ ``` python
144
+ class NodeCircle :
145
+ def __init__ (self , val ):
146
+ self .val = val
147
+ self .next = None
148
+
149
+ def has_circle (self , head ):
150
+ slow = head
151
+ fast = head
152
+ while (slow and fast):
153
+ fast = fast.next
154
+ slow = slow.next
155
+ if fast:
156
+ fast = fast.next
157
+ if fast == slow:
158
+ break
159
+ if fast and slow and (fast == slow):
160
+ return True
161
+ else :
162
+ return False
163
+ ```
You can’t perform that action at this time.
0 commit comments