Skip to content

Commit a68657e

Browse files
committedJan 19, 2022
Add solution #142
1 parent 787b7d9 commit a68657e

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@
7575
133|[Clone Graph](./0133-clone-graph.js)|Medium|
7676
136|[Single Number](./0136-single-number.js)|Easy|
7777
141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy|
78+
142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium|
7879
144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy|
7980
145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy|
8081
151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium|
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* 142. Linked List Cycle II
3+
* https://leetcode.com/problems/linked-list-cycle-ii/
4+
* Difficulty: Medium
5+
*
6+
* Given the head of a linked list, return the node where the cycle begins.
7+
* If there is no cycle, return null.
8+
*
9+
* There is a cycle in a linked list if there is some node in the list that
10+
* can be reached again by continuously following the next pointer. Internally,
11+
* pos is used to denote the index of the node that tail's next pointer is
12+
* connected to (0-indexed). It is -1 if there is no cycle. Note that pos is
13+
* not passed as a parameter.
14+
*
15+
* Do not modify the linked list.
16+
*/
17+
18+
/**
19+
* Definition for singly-linked list.
20+
* function ListNode(val) {
21+
* this.val = val;
22+
* this.next = null;
23+
* }
24+
*/
25+
26+
/**
27+
* @param {ListNode} head
28+
* @return {ListNode}
29+
*/
30+
var detectCycle = function(head) {
31+
while (head) {
32+
if (head.visited) {
33+
return head;
34+
}
35+
head.visited = 1;
36+
head = head.next;
37+
}
38+
return head;
39+
};

0 commit comments

Comments
 (0)
Please sign in to comment.