https://leetcode.com/problems/linked-list-cycle/#/description
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Sol:
To solve this problem we will have two markers traversing through the list. marker1 and marker2. We will have both makers begin at the first node of the list and traverse through the linked list. However the second marker, marker2, will move two nodes ahead for every one node that marker1 moves.
By this logic we can imagine that the markers are "racing" through the linked list, with marker2 moving faster. If the linked list has a cylce and is circularly connected we will have the analogy of a track, in this case the marker2 will eventually be "lapping" the marker1 and they will equal each other.
If the linked list has no cycle, then marker2 should be able to continue on until the very end, never equaling the first marker.
Let's see this logic coded out:
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ p_slow = head p_fast = head while p_fast != None and p_fast.next != None: p_slow = p_slow.next p_fast = p_fast.next.next if p_slow == p_fast: return True return False
Note:
1 Intialize two pointers by setting them as input variable head or node.
2 To advance pointers, the right syntax is;
pointer = pointer.next
It update itself.... do not forget to intialize them beforehand.