题解 | #链表中环的入口结点#

链表中环的入口结点

https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4

package main

/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

func EntryNodeOfLoop(pHead *ListNode) *ListNode {
    if pHead == nil || pHead.Next == nil {
        return nil
    }
	temp := pHead
	fast, slow := temp, temp
	for fast != nil && fast.Next != nil {
		slow = slow.Next
		fast = fast.Next.Next
		if slow == fast {
			break
		}
	}
	if slow != fast {
		return nil
	}
	fast = pHead
	for fast != slow {
		fast = fast.Next
		slow = slow.Next
	}
	return fast
}

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务