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
相关产品推荐
相关产品推荐

