题解 | #链表中环的入口节点#
链表中环的入口节点
http://www.nowcoder.com/practice/6e630519bf86480296d0f1c868d425ad
- 快指针的判断,『技巧』
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *detectCycle(ListNode *head) { if( nullptr==head || nullptr==head->next ) { return nullptr; } ListNode * fast=head; ListNode * low=head; while( 1 ) { //核心代码 if( nullptr!=fast && nullptr!=fast->next ) { fast=fast->next->next; } else { return nullptr;//有终点,必然是 } low=low->next; if( low==fast ) { break; } } ListNode * Help=head; while( 1 ) { if( Help==low ) { return low; } else { Help=Help->next; low=low->next; } } return nullptr;//给编译器吃 } };