领扣LintCode算法问题答案-1609. 链表的中间结点

    科技2022-07-13  137

    领扣LintCode算法问题答案-1609. 链表的中间结点

    目录

    1609. 链表的中间结点描述样例 1:样例 2: 题解鸣谢

    1609. 链表的中间结点

    描述

    给定一个带有头结点 head 的非空单链表,返回链表的中间结点。

    如果有两个中间结点,则返回第二个中间结点。

    The number of nodes in the given list will be between 1 and 100.

    样例 1:

    输入:1->2->3->4->5->null 输出:3->4->5->null

    样例 2:

    输入:1->2->3->4->5->6->null 输出:4->5->6->null

    题解

    /** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /** * @param head: the head node * @return: the middle node */ public ListNode middleNode(ListNode head) { // write your code here. List<ListNode> ll = new ArrayList<>(); while (head != null) { ll.add(head); head = head.next; } int index = ll.size() / 2; return ll.get(index); } }

    原题链接点这里

    鸣谢

    非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。 欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

    Processed: 0.009, SQL: 8