[LeetCode] 141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Can you solve it without using extra space?
Thought process:
Use fast and slow pointers. If there is a cycle, fast will enter it first, and loop through the cycle. After slow enters the cycle, there will be an iteration where two pointers collide. If there's no cycle, fast will exit the linked list.
Solution:
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 27 28 29 30 31 32 | /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { if (head == null) { return false; } ListNode fast = head.next; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) { return true; } } return false; } } |
Time complexity:
If there is a cycle, fast will pursue slow with a speed difference of one node per iteration. So it will take fast less than "number of nodes in cycle" iterations to meet slow. The overall time complexity is O(n).
Comments
Post a Comment