{ "cells": [ { "cell_type": "markdown", "source": [ "Given a non-empty, singly linked list with head node `head`, return a middle\n", "node of linked list.\n", "\n", "If there are two middle nodes, return the second middle node.\n", "\n", "\n", "\n", "**Example 1:**\n", "\n", "\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", "**Example 2:**\n", "\n", "\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", " * The number of nodes in the given list will be between `1` and `100`." ], "metadata": {} }, { "outputs": [ { "output_type": "execute_result", "data": { "text/plain": "middle_node_by_double_pointers (generic function with 1 method)" }, "metadata": {}, "execution_count": 1 } ], "cell_type": "code", "source": [ "# @lc code=start\n", "using LeetCode\n", "\n", "# double pointers\n", "function middle_node_by_double_pointers(head::ListNode)::ListNode\n", " p1 = p2 = head\n", " while !isnothing(p2)\n", " p2 = next(p2)\n", " isnothing(p2) && return p1\n", " p2, p1 = p2.next, p1.next\n", " end\n", " return p1\n", "end\n", "\n", "# @lc code=end" ], "metadata": {}, "execution_count": 1 }, { "cell_type": "markdown", "source": [ "---\n", "\n", "*This notebook was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*" ], "metadata": {} } ], "nbformat_minor": 3, "metadata": { "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "1.10.1" }, "kernelspec": { "name": "julia-1.10", "display_name": "Julia 1.10.1", "language": "julia" } }, "nbformat": 4 }