aboutsummaryrefslogtreecommitdiff
path: root/middle_linked_list.py
blob: d3c676270ad4af434a2d80b9ac9667d1317a8b8b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 876. Middle of the Linked List

"""
given the head of a singly linked list, return the middle of the node of the
linked list. if there are two middle nodes, return the second middle node.
"""

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution(object):
    def middleNode(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        slow, fast = head, head
        while fast:
            fast = fast.next
            if fast:
                fast = fast.next
                slow = slow.next
        return slow