You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java单向链表:如何按用户输入的节点数录入元素并正反向打印

Java单向链表动态输入及反转实现修改方案

修改核心步骤

  • 补充java.util.Scanner包导入,修复原代码拼写错误的输入提示
  • 移除硬编码的1-5节点创建逻辑,替换为根据用户输入的节点数动态构建链表的逻辑
  • 调整display方法输出格式,移除末尾多余的null输出,匹配预期运行效果

修改后完整代码

import java.util.Scanner;

public class LinkedList 
{
    private Node head;
    private Node current;
    
    private static class Node
    {
        private int data;
        private Node next;
        
        public Node(int data)
        {
            this.data = data;
            this.next = null;
        }
    }
    
    public void display()
    {
        Node current = head;
        while (current != null)
        {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
    
    public void reverse()
    {
        Node next = head;
        Node previous = null;
        current = null;
        
        while(next != null)
        {
            current = next;
            next = next.next;
            
            current.next = previous;
            previous = current;
            head = current;
        }
    }
    
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        LinkedList list = new LinkedList();
        
        System.out.print("Input the number of nodes : ");
        int size = sc.nextInt();
        
        // 动态读取用户输入构建链表
        Node tail = null;
        for (int i = 1; i <= size; i++) {
            System.out.print("Input data for node " + i + " : ");
            int data = sc.nextInt();
            Node newNode = new Node(data);
            if (list.head == null) {
                list.head = newNode;
                tail = newNode;
            } else {
                tail.next = newNode;
                tail = newNode;
            }
        }
        sc.close();
        
        System.out.print("Data entered in the list are : ");
        list.display();
        
        list.reverse();
        
        System.out.print("The list in reverse are : ");
        list.display();
    }
}

关键逻辑说明

  • 动态构建链表时使用tail指针记录当前链表尾部节点,每次新增节点直接挂到尾部,避免每次遍历链表找尾节点,提升构建效率
  • 反转逻辑沿用原有实现,不需要修改即可正常工作
  • 所有输入输出提示完全匹配预期运行示例

内容的提问来源于stack exchange,提问作者Nico Ni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 19:15:01