LeetCode876 question: The middle node of the linked list Given a non-empty singly linked list with the head node as head, return the middle node of the linked list. If there are two intermediate nodes, return to the second intermediate node.

  1. The middle node of the linked list
    Given a non-empty singly linked list with the head node as head, return the middle node of the linked list.

If there are two intermediate nodes, return to the second intermediate node.

Example 1:

输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3(测评系统对该结点序列化表述是 [3,4,5])
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.

Example 2:

输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
由于该列表有两个中间结点,值分别为 34,我们返回第二个结点。

prompt:

The number of nodes in a given linked list is between 1 and 100.
Code:

/**
 * 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 fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
    
    //两种情况同时满足
            fast = fast.next.next;//fast每次走两步
            slow = slow.next;//slow每次走一步
        }
        return slow;//返回slow
    }
}

result;
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44436675/article/details/112431918