Description of the entry node of the link in the linked list
A linked list contains the ring, please find the link to the list of the entry node.
Ideas
- If the list exists ring, set two pointers pslow and Pfast,pslow each step, pfast each walk two steps, when pfast catch up Pslow, pfast more than Pslow walk is just pslow walk is the number of nodes contained in the ring.
- So, the second walk, a start from the beginning, the other from the meeting node, will eventually meet in the ring entrance node
Code
/* public class ListNode {int val; ListNode next = null; ListNode (int val) {this.val = val; }}*/PublicClass Solution {Public ListNode Entrynodeofloop (ListNode phead) {if (Phead = =NULL) {ReturnNull }listnode pslow = Phead; ListNode pfast = Phead;do {if (Pfast. Next = = null) {return null; //has a null value indicating that the linked list has no ring}pslow = Pslow. next;pfast = pfast. next; if (Pfast. Next = = null) {return null; //has a null value indicating that the linked list has no ring}pfast = Pfast. next;} while (pslow! = pfast);p slow = phead; while (pslow! = pfast) {Pslow = Pslow. Next;pfast = Pfast. next;} return Pslow;}
The entry node of the ring in the linked list-the offer of the sword *