java链表的中间结点

题目:链表的中间结点,给定一个头结点为 head 的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。
链表中间节点

1.分析

  1. 遍历单链表一遍,定义两个引用fastslowfast表示数度是slow的两倍,最后一个到结尾,一个就到中间位置了。
  2. fast一次走两步,slow一次走一步。
  3. 首先判断head是否为空
  4. 定义两个引用fastslow都指向头结点
  5. 因为fast一次走两步,所以要判断fastfast.next是否为空,并且fast必须写在前面,因为如果fast.next如果写在前面,fast本身为空就会报空指针异常。为空返回slow
  6. 不为空的话fast=fast.next.next;slow=slow.next;执行5

2.具体步骤

奇数个:
在这里插入图片描述
偶数个:
在这里插入图片描述

3.代码

public ListNode middleNode() {
    
    //返回中间节点,偶数个返回中间第二个
        if (head == null) {
    
    
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;

        while (fast != null && fast.next != null) {
    
    
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

测试:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44721738/article/details/121178843
今日推荐