Post

Leetcode - 876. Middle of the Linked List

Leetcode - 876. Middle of the Linked List

Hits

  • Given the head of a singly linked list, return the middle node of the linked list.

    If there are two middle nodes, return the second middle node.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func middleNode(head *ListNode) *ListNode {
    if head==nil{
        return head
    }

    fastPointer := head
    slowPointer := head

    for fastPointer!=nil && fastPointer.Next!=nil{
        slowPointer = slowPointer.Next
        fastPointer = fastPointer.Next.Next
    }

    return slowPointer
}
This post is licensed under CC BY 4.0 by the author.