当前位置: 代码迷 >> 综合 >> LeetCode 876. Middle of the Linked List返回链表的中间结点
  详细解决方案

LeetCode 876. Middle of the Linked List返回链表的中间结点

热度:89   发布时间:2023-11-24 04:07:55.0

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

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

在这里插入图片描述
二、代码实现

/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/
class Solution {
    public ListNode middleNode(ListNode head) {
    ListNode node = head;int len = getLength(head);for (int i = 0; i < len / 2; i++) {
    node = node.next;}return node;}private int getLength(ListNode head){
    int len = 0;while(head != null){
    len ++;head = head.next;}return len;}
}
  相关解决方案