/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/funcmiddleNode(head*ListNode)*ListNode{ifhead==nil{returnhead}slow,fast:=head,headforfast!=nil&&fast.Next!=nil{slow=slow.Nextfast=fast.Next.Next}returnslow}
拓展:如果有两个中间结点,返回第一个中间结点的代码实现如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/funcmiddleNode(head*ListNode)*ListNode{ifhead==nil{returnhead}slow,fast:=head,headforfast.Next!=nil&&fast.Next.Next!=nil{slow=slow.Nextfast=fast.Next.Next}returnslow}