阿里 LeetCode 876.链表的中间节点

附代码:

java 复制代码
class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode fast = head,slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}

ACM模式:

java 复制代码
import java.util.Scanner;

class ListNode {
    int val;
    ListNode next;
    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] nums = new int[n];
        for(int i = 0;i < n;i++){
            nums[i] = scanner.nextInt();
        }
        ListNode head = null;
        if(n > 0){
            head = new ListNode(nums[0]);
            ListNode cur = head;
            for(int i = 1;i < n;i++){
                cur.next = new ListNode(nums[i]);
                cur = cur.next;
            }
        }
        Solution solution = new Solution();
        ListNode mid = solution.middleNode(head);
        System.out.println(mid.val);
        scanner.close();
    }
}
class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode fast = head, slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}
相关推荐
forest_093 小时前
《AI 编程 Harness 实战手册》04|审批这道门:点了一百次“允许”,还剩多少作用?
人工智能·算法·prompt·agi
H.莓飛3 小时前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
不会武功不懂江湖6 小时前
RISC-V链接器与链接脚本
汇编·算法·risc-v
Zwawa7 小时前
卡尔曼到底在算什么:从一维到它的变式以及工程版卡尔曼滤波算法C语言实现
c语言·算法·嵌入式
电科_银尘7 小时前
【大模型算法与工程 14】Tokenizer与Embedding:文本如何变成模型输入
算法·embedding
饮水桶_T8 小时前
Python 面向对象(十七)|继承、封装、多态 笔记
数据结构·笔记·算法
文丑颜不良啊10 小时前
LeetCode3281~3300题目解析
java·leetcode
地平线开发者11 小时前
让 AI Agent 和 征程6 台架高效、稳定、安全地协作
算法·安全·自动驾驶
kyle~12 小时前
SHA-256 哈希去重
算法·哈希算法