0141. Linked List Cycle
难度: Easy
刷题内容
原题连接
- 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.
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.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
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%
代码:
/**
* 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
};