链表中环的入口结点
给定一个链表,若其中包含环,则输出环的入口节点。
若其中不包含环,则输出null。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *entryNodeOfLoop(ListNode *head) {
auto a = head, b = head;
while (b) {
a = a->next;
b = b->next;
if (b) b = b->next;
else return NULL;
if (a == b) {
a = head;
while (a != b) {
a = a->next;
b = b->next;
}
return a;
}
}
return NULL;
}
};

浙公网安备 33010602011771号