https://oj.leetcode.com/problems/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?
/*** Definition for singly-linked list. * Class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; * } * } */ Public classSolution { Public Booleanhascycle (ListNode head) {if(Head = =NULL|| Head.next = =NULL){ return false; } while(Head.next! =NULL){ if(Head.next = =head) { return true; } ListNode Temp=Head.next; Head.next=Head.next.next; Temp.next=Head; } return false; }}
Problem Solving Ideas:
If Next of the head node does not point to the current node, delete the next node (next on the current node, next on the next node) until return true is found. Otherwise, the next node is null, it proves the end, there is no loopback, return false. Head node never move, in fact, is to delete the back.
There are two problems in doing so, the first value considers the situation of the 1,2,3,1, without considering that the loopback may be in the middle, that is, 1,2,3,4,2. This is going to be a dead loop, because 1! =2, the loop will never stop. Second, it will change the original list structure,
The first question, next node next does not point to the current node, do not delete, the next point to the head node, so that if there is a loopback, no matter who he points to, because the front has been pointed to the head, the final can always be judged.
The second problem, you can use speed running method. Starting at head, fast hands take two steps at a time, slow one step at a time. If there is a loopback, they will certainly have one day pointing to the same node, and if not, fast to null will end.
Linked List Cycle