1 题目;
链表中环的入口结点_牛客题霸_牛客网 (nowcoder.com)
2 参考:
链表中环的入口结点_牛客题霸_牛客网 (nowcoder.com)
3 代码:
C++
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
#include <cstddef>
class Solution {
public:
ListNode* hasCycle(ListNode *head){
if (head == NULL) return NULL;
ListNode* f = head;
ListNode* s = head;
while (f != NULL && f->next != NULL) {
f = f->next->next;
s = s->next;
if (f == s)
return s;
}
return NULL;
}
ListNode* EntryNodeOfLoop(ListNode* pHead) {
ListNode *s = hasCycle(pHead);
if(s == NULL)
return NULL;
ListNode* f = pHead;
while (f != s) {// X = n * (Y + Z) -Y
f = f->next;
s = s->next;
}
return s;
}
};
Python3:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
s = self.hasCycle(pHead)
if s == None:
return None
f = pHead
while f != s:
f = f.next
s = s.next
return s
def hasCycle(self, head):
if head == None:
return None
f = head
s = head
while f != None and f.next != None:
f = f.next.next
s = s.next
if f == s:
return s
return None