BM7 链表中环的入口结点
作者:互联网
解题思路:声明两个指针,快指针一次走两步,慢指针一次走一步
最后的结论是:有环的话两个指针一定会相遇,且相遇点到环口的距离=起点到环口的距离
所以相遇之后,慢指针走一步,头结点走一步,最后一定会在环的入口相遇
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
ListNode fast = pHead;
ListNode slow = pHead;
boolean flag = false;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
flag = true;
break;
}
}
if (!flag) {
return null;
}
while (pHead != slow) {
pHead = pHead.next;
slow = slow.next;
}
return pHead;
}
}
标签:结点,slow,ListNode,fast,next,链表,pHead,BM7,null 来源: https://blog.csdn.net/liulong999/article/details/123598693