0141._Linked_List_Cycle.md 2.3 KB
Newer Older
W
wangchong 已提交
1
# 0141. Linked List Cycle
W
wangchong 已提交
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/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 tail connects to. If pos is -1, then there is no cycle in the linked list.
```

**Example 1:**

```
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.
```

![img](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png)

**Example 2:**

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

![img](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png)

**Example 3:**

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

![img](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png)

 

**Follow up:**

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



## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******

使用`快慢指针`的思路进行解题。就像两个运动员在同一个环形赛道上赛跑,如果一个运动员跑的快,一个跑得慢,最后两个运动员一定会相遇。

下面代码中的`fast`每次会走两步,而`slow`每次会走一步,如果`fast`没有`next`节点,自然没有环;如果`fast`等于`slow`说明二者相遇,最终为表明存在环。



#### 执行结果

执行用时 :**92 ms**, 在所有 JavaScript 提交中击败了94.16%的用户

内存消耗 :**36.6 MB**, 在所有 JavaScript 提交中击败了51.93%



代码:

```javascript
/**
 * 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 === null || head.next === null) {
    return false
  }
  
  let slow = head
  let fast = head.next
  
  while (slow !== fast) {
    if (fast === null || fast.next === null) {
      return false
    }
    slow = slow.next
    fast = fast.next.next
  }
  return true
};
```