Test instructions: Gives a single-linked list, if it has a ring, returns the pointer at the beginning of the ring, if no ring returns NULL.
Ideas:
(1) Still use two pointers to catch up to determine whether there is a ring. After the determination of the ring, the pointer 1 runs half of the pointer 2, and they have run over an overlapping road (that is, 1 ran, 2 also ran), that paragraph (the beginning of the ring, meet place), then the pointer 2 starts to the ring from the beginning of the distance and head to the hands of the meeting is the same length oh ~, Then run again every step of the meeting will certainly meet. Drawing a tutu is easy to see.
(2) In fact, there is another intuitive way of thinking, that is, the pointer 1 and 2 after the encounter, P point to their next, in their encounter where the next to set empty, and then run again that "find two linked list of the beginning of the second half of the overlap" that the problem on the line.
(1) Code
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: OneListNode *detectcycle (ListNode *head) { A if(!head)return 0; -ListNode *one=head, *two=head->Next; - while(two&&two->next&&one!=Both ) the { -One=one->Next; -Two=two->next->Next; - } + if(!two| |! Two->next)return 0;//No ring -two=two->next;//at this point they have met, and one step after the other, so that both and head to the same length. + while(Head!=two)//must have met A { atHead=head->Next; -Two=two->Next; - } - returnhead; - } -};
AC Code
(2) Code
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: OneListNode *detectcycle (ListNode *head) { A if(!head)return 0; -ListNode *one=head, *two=head->Next; - while(two&&two->next&&one!=Both ) the { -One=one->Next; -Two=two->next->Next; - } + if(!two| |! Two->next)return 0;//No ring -one=one->next;//At this point, the other is at the fracture +two->next=0; A atListNode * P1=one, *p2=head; - while(P1 && p2 && p1!=p2)//two linked list find overlap ~ even if the p1p2 to start overlap is not long can be solved - { -P1=p1->Next; -P2=p2->Next; - in if(!P1) p1=head; - if(!P2) p2=One ; to } +two->next=One ; - returnP1; the } *};
AC Code
Leetcode Linked List Cycle II single-link ring 2 (find loop start)