{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "

876. Middle of the Linked List

\n", "
\n", "\n", "\n", "

Given a non-empty, singly linked list with head node head, return a middle node of linked list.

\n", "\n", "

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

\n", "\n", "

 

\n", "\n", "
\n", "

Example 1:

\n", "\n", "
Input: [1,2,3,4,5]\n",
    "Output: Node 3 from this list (Serialization: [3,4,5])\n",
    "The returned node has value 3.  (The judge's serialization of this node is [3,4,5]).\n",
    "Note that we returned a ListNode object ans, such that:\n",
    "ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.\n",
    "
\n", "\n", "
\n", "

Example 2:

\n", "\n", "
Input: [1,2,3,4,5,6]\n",
    "Output: Node 4 from this list (Serialization: [4,5,6])\n",
    "Since the list has two middle nodes with values 3 and 4, we return the second one.\n",
    "
\n", "\n", "

 

\n", "\n", "

Note:

\n", "\n", "\n", "
\n", "
\n", "\n", "\n", "

 

\n", "Source \n", "
" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# Definition for singly-linked list.\n", "class ListNode:\n", " def __init__(self, val=0, next=None):\n", " self.val = val\n", " self.next = next" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Code

" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def middle_node(head):\n", " \"\"\"Naive solution: Counting the number of nodes\"\"\"\n", " node = head\n", "\n", " counter = 0\n", " while node.next:\n", " counter += 1\n", " node = node.next\n", "\n", " counter = (counter+1) // 2 # counter+1 to account for the last node\n", " node = head\n", " while counter > 0:\n", " counter -= 1\n", " node = node.next\n", " return node" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def middle_node(head):\n", " \"\"\"Using 2 pointers.\"\"\"\n", " if head is None:\n", " return head\n", " slow, fast = head, head\n", " while fast and fast.next:\n", " slow = slow.next\n", " fast = fast.next.next\n", " return slow" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.2" } }, "nbformat": 4, "nbformat_minor": 1 }