Golang Leetcode 876. Middle of the Linked List.go

2019-05-05 11:54:21 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1420473

思路

快慢指针,快指针走两步,满指针走一步

code

代码语言:javascript复制
type ListNode struct {
	Val  int
	Next *ListNode
}
func middleNode(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}
	fast := head
	slow := head
	for fast != nil {
		if fast.Next == nil {
			break
		}
		fast = fast.Next
		slow = slow.Next
		if fast.Next != nil {
			fast = fast.Next
		}
	}
	return slow
}

0 人点赞