Skip to content

Commit 8d3681f

Browse files
committed
添加py和js
1 parent 98bf6de commit 8d3681f

File tree

1 file changed

+59
-15
lines changed

1 file changed

+59
-15
lines changed

animation-simulation/链表篇/leetcode142环形链表2.md

Lines changed: 59 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -197,21 +197,21 @@ public class Solution {
197197
public ListNode detectCycle(ListNode head) {
198198
//快慢指针
199199
ListNode fast = head;
200-
ListNode low = head;
200+
ListNode slow = head;
201201
//设置循环条件
202202
while (fast != null && fast.next != null) {
203203
fast = fast.next.next;
204-
low = low.next;
204+
slow = slow.next;
205205
//相遇
206-
if (fast == low) {
206+
if (fast == slow) {
207207
//设置一个新的指针,从头节点出发,慢指针速度为1,所以可以使用慢指针从相遇点出发
208-
ListNode newnode = head;
209-
while (newnode != low) {
210-
low = low.next;
211-
newnode = newnode.next;
208+
ListNode newptr = head;
209+
while (newptr != slow) {
210+
slow = slow.next;
211+
newptr = newptr.next;
212212
}
213213
//在环入口相遇
214-
return low;
214+
return slow;
215215
}
216216
}
217217
return null;
@@ -227,26 +227,70 @@ public:
227227
ListNode *detectCycle(ListNode *head) {
228228
//快慢指针
229229
ListNode * fast = head;
230-
ListNode * low = head;
230+
ListNode * slow = head;
231231
//设置循环条件
232232
while (fast != nullptr && fast->next != nullptr) {
233233
fast = fast->next->next;
234-
low = low->next;
234+
slow = slow->next;
235235
//相遇
236-
if (fast == low) {
236+
if (fast == slow) {
237237
//设置一个新的指针,从头节点出发,慢指针速度为1,所以可以使用慢指针从相遇点出发
238238
ListNode * newnode = head;
239-
while (newnode != low) {
240-
low = low->next;
239+
while (newnode != slow) {
240+
slow = slow->next;
241241
newnode = newnode->next;
242242
}
243243
//在环入口相遇
244-
return low;
244+
return slow;
245245
}
246246
}
247247
return nullptr;
248-
249248
}
250249
};
251250
```
252251
252+
JS Code:
253+
254+
```js
255+
var detectCycle = function(head) {
256+
let fast = head;
257+
let slow = head;
258+
while (fast && fast.next) {
259+
fast = fast.next.next;
260+
slow = slow.next;
261+
if (fast == slow) {
262+
let newptr = head;
263+
while (newptr != slow) {
264+
slow = slow.next;
265+
newptr = newptr.next;
266+
}
267+
return slow;
268+
}
269+
}
270+
return null;
271+
};
272+
```
273+
274+
Python Code:
275+
276+
```py
277+
class Solution:
278+
def detectCycle(self, head: ListNode) -> ListNode:
279+
# 快慢指针
280+
fast = head
281+
slow = head
282+
# 设置循环条件
283+
while fast is not None and fast.next is not None:
284+
fast = fast.next.next
285+
slow = slow.next
286+
# 相遇
287+
if fast is slow:
288+
# 设置一个新的指针,从头节点出发,慢指针速度为1,所以可以使用慢指针从相遇点出发
289+
newptr = head
290+
while newptr is not slow:
291+
slow = slow.next
292+
newptr = newptr.next
293+
# 在环入口相遇
294+
return slow
295+
```
296+

0 commit comments

Comments
 (0)