题解 | #JZ23 链表中环的入口结点#
链表中环的入口结点
http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
//遍历后的节点全部指向-1,当下一个节点指向-1时自然是环入口
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
ListNode *node = pHead;
while (node) {
if (node->next == (ListNode*)-1) { //节点指向-1表示被遍历过,即环入口
return node;
} else {
ListNode *tmp = node;
node = node->next;
tmp->next = (ListNode*)-1; //全部指向-1
}
}
return NULL;
}
}; 