LintCode: Middle of Linked List

Middle of Linked List



Similar Problems:


Description
Find the middle node of a linked list.

Example
Given 1->2->3, return the node with value 2.

Given 1->2, return the node with value 1.

Follow-up:
Instead of solving it by two-pass. Can you do it in one-pass?

Github: code.dennyzhang.com

Credits To: lintcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
## Blog link: https://code.dennyzhang.com/middle-of-linked-list
## Basic Ideas: fast/slow pointers
## Complexity: Time O(n), Space O(1)
"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


class Solution:
    """
    @param: head: the head of linked list.
    @return: a middle node of the linked list
    """
    def middleNode(self, head):
        slow, fast = head, head
        while fast and fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        return slow
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.