Voyz's Studio.

LeetCode算法笔记--环形链表

字数统计: 279阅读时长: 1 min
2021/01/03 Share

LeetCode算法笔记-Day57

141. Linked List Cycle

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where the tail connects to. If pos == -1, then there is no cycle in the linked list.

Can you solve it using O(1) (i.e. constant) memory?

1
2
3
4
5
6
7
8
9
10
11
12
13
example:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

方法一:快慢指针

Analyse:

  • 类似“追及问题”
  • 两个人在环形跑道上赛跑,同一个起点出发,一个跑得快一个跑得慢,在某一时刻,跑得快的必定会追上跑得慢的,只要是跑道是环形的,不是环形就肯定追不上。  

Answer:

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
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/

/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
if(!head) return false;
let p_slow = head;
let p_fast = head;

while(p_fast){
if(!p_fast.next) return false;
p_fast = p_fast.next.next;
p_slow = p_slow.next;
if(p_slow == p_fast) return true;
}

return false;
};
CATALOG
  1. 1. LeetCode算法笔记-Day57
    1. 1.1. 141. Linked List Cycle
    2. 1.2. 方法一:快慢指针
      1. 1.2.1. Analyse:
      2. 1.2.2. Answer: