题目描述
https://leetcode.cn/problems/middle-of-the-linked-list/description/
给你单链表的头结点 head
,请你找出并返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
示例 1:

示例 2:

思路分析
用两个指针 slow
与 fast
一起遍历链表。slow
一次走一步,fast
一次走两步。那么当 fast
到达链表的末尾时,slow
必然位于中间。
代码实现
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/ class Solution {public ListNode middleNode(ListNode head) {if(head==null) return null;ListNode slow = head, fast = head;while(fast!=null && fast.next!=null){slow = slow.next;fast = fast.next.next;}return slow;} }