Given A linked list, determine if it has a cycle in it.
Follow Up:can you solve it without using extra space?
From the sword Point offer: When using a pointer to traverse the list does not solve the problem, you can try to use two pointers to traverse the linked list, you can let a pointer traverse faster, or let him walk a number of steps on the list.
The related topics are:
To find the middle node of a linked list,
Determine if a one-way linked list forms a circular structure
Determine the entry node of a ring with a linked list
A traverse to the bottom of the list K nodes
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
Determine if there is a ring code as follows:
public boolean hascycle (ListNode head) { ListNode slow = head; ListNode fast = head; if (head==null| | Head.next==null) { return false; } while (slow.next!=null&&fast.next!=null&&fast.next.next!=null) { slow = Slow.next; Fast = Fast.next.next; if (slow==fast) { return true; } } return false; }
Judging the entry point of the ring:
And the sword refers to the offer of the 56th question, is also used two pointers, the first pointer from the head to go forward the number of nodes in the ring, the second pointer to head, two pointers at the same speed forward, know that two pointers meet is the ring entry point.
First you must know the number of nodes in the ring, you can use the above problem, find two pointers meet the place is a node in the ring, and then start counting.
The code is as follows:
Public ListNode detectcycle (ListNode head) { ListNode Meetnode = Meet (head); int nodeloop = 1; ListNode node1 = Meetnode; if (node1==null) { return null; } while (Node1.next!=meetnode) { node1 = Node1.next; Nodeloop = Nodeloop + 1; } ListNode node2 = head; for (int i = 0;i<nodeloop;i++) { node2 = node2.next; } ListNode node3 = head; while (NODE2!=NODE3) { node2 = Node2.next; Node3 = Node3.next; } return node2; } Public ListNode Meet (ListNode head) { ListNode slow = head; ListNode fast = head; if (head==null| | Head.next==null) { return null; } while (slow.next!=null&&fast.next!=null&&fast.next.next!=null) { slow = Slow.next; Fast = Fast.next.next; if (slow==fast) { return slow; } } return null; }
Leetcode linked list cycle and linked list cycle II