AcWing打卡活动
《剑指Offer》打卡活动
周二第十一题 链表中环的入口结点
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
* 思路
* a. 确定是否是环链表
* 使用两个节点,一个节点一次走一步,一个节点一次走2步,
* 这样如果链表中有环的话,走两步的节点是可以追上走一步的节点的
* b. 确定环的大小,即环中有多少元素
* 利用刚刚mettingNode()得到的相遇节点
* 依旧使用两个节点,一个节点停留在相遇节点,一个节点从相遇节点出发
* 计数器++,直到两个节点相遇
* c. 确定环的入口节点
* 两个节点p1和p2, p1向前移动N(N=环中元素数)步,p2停留在头结点
* p1和p2同时移动,直到相遇
* 例子:
* 1 2 3 4 5 6
* 从4~6为环
* 则环中有3个节点,
* 第一步、p1 先走3步,从节点4出发,p2 从头结点出发
* 第二步、p1,p2同时出发,一起走3步,p1 -> 1, 2, 3, 4, p2 -> 4, 5, 6, 4 相遇
*
*
*/
class Solution {
public ListNode entryNodeOfLoop(ListNode head) {
if(head == null) {
return null;
}
// a.确定是否有环,拿到相遇节点
ListNode metNode = meetingNode(head);
if(metNode == null) {
return null;
}
// b. 确定环中的元素数
ListNode node = metNode.next;
int nodesInLoop = 1;
while(node != metNode) {
node = node.next;
nodesInLoop++;
}
// c、确定环的入口节点,需要两个节点, 从头开始走
node = head;
ListNode node2 = head;
for(int i = 0; i < nodesInLoop; i++) {
node = node.next;
}
// 一起走
while(node != node2) {
node = node.next;
node2 = node2.next;
}
return node;
}
// a. 确定是否有环
public ListNode meetingNode(ListNode head) {
if(head == null) {
return null;
}
ListNode slowNode = head;
slowNode = slowNode.next;
if(slowNode == null) {
return null;
}
ListNode fastNode = slowNode.next;
// 开始追
while(fastNode != null && slowNode != null) {
if(fastNode == slowNode) {
return fastNode;
}
// 一次走一步
slowNode = slowNode.next;
// 一次走两步
fastNode = fastNode.next;
if(fastNode != null) {
fastNode = fastNode.next;
}
}
// 如果出了while,则该链表没有环
return null;
}
}