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?
环形链表。
题意很简单,思路是用快慢指针,慢指针每走一步,快指针走两步。如果快慢指针在某个地方相遇了,说明有环;否则快指针就会遍历到链表尾部从而会退出循环。
时间O(n)
空间O(1)
JavaScript实现
1 /** 2 * @param {ListNode} head 3 * @return {boolean} 4 */ 5 var hasCycle = function(head) { 6 // corner case 7 if (head === null || head.next === null) { 8 return false; 9 } 10 11 // normal case 12 let slow = head; 13 let fast = head; 14 while (fast !== null && fast.next !== null) { 15 slow = slow.next; 16 fast = fast.next.next; 17 if (slow === fast) { 18 return true; 19 } 20 } 21 return false; 22 };
Java实现
1 public class Solution { 2 public boolean hasCycle(ListNode head) { 3 // corner case 4 if (head == null || head.next == null) { 5 return false; 6 } 7 8 // normal case 9 ListNode slow = head; 10 ListNode fast = head; 11 while (fast != null && fast.next != null) { 12 slow = slow.next; 13 fast = fast.next.next; 14 if (slow == fast) { 15 return true; 16 } 17 } 18 return false; 19 } 20 }