https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4?tpId=13&tqId=11208&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
and
https://leetcode.com/problems/linked-list-cycle-ii/
日期 | 是否一次通过 | comment |
---|---|---|
2019-02-09 20:20 | N | 知道方法,但是实现太鸡毛 |
2019-02-10 12:20 | Y | 真的很easy |
题目:判断单链表是否有环,并输出环入口
思路:
- 快慢指针是否相遇判断有环与否;
- 两指针同速,分别从起点和相遇点开始遍历,再次相遇的点即为环入口
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
if(pHead == null || pHead.next == null) {
return null;
}
ListNode pSlow = pHead;
ListNode pFast = pHead;
while(pFast != null && pFast.next != null) {
pSlow = pSlow.next;
pFast = pFast.next.next;
if(pSlow == pFast) {
pSlow = pHead;
while(pSlow != pFast) {
pSlow = pSlow.next;
pFast = pFast.next;
}
return pSlow;
}
}
return null;
}
}
网友评论