Java自定义LinkedList数组参数构造器实现失败问题
链表实现问题修复说明
核心错误点
- 数组参数构造器未初始化头结点,初始
head == null,直接调用tmp.getNext()会触发NullPointerException - 遍历数组过程中没有创建新的
Node对象,没有完成节点挂载逻辑 printList方法没有做空链表判断,空链表调用直接报错- 原有打印逻辑用
println会把每个节点拆成单独行输出,不符合链表常规打印格式
修复后代码
Node.java(原有逻辑无问题可直接复用)
import java.lang.*; public class Node { private int value; private Node next; public Node(){ this.value = 0; this.next = null; } public Node(int value){ this.value = value; this.next = null; } public Node(int value, Node next){ this.value = value; this.next = next; } public Node getNext(){ return this.next; } public int getValue(){ return this.value; } public void setNext(Node next){ this.next = next; } public void setValue(int value){ this.value = value; } public String toString(){ return this.value + "_" + this.next; } }
IntLinkedList.java(核心逻辑修复)
import java.lang.*; import java.util.*; public class IntLinkedList { private Node head; public IntLinkedList(){ this.head = null; } public IntLinkedList(int[] intArray){ // 入参为空直接返回 if(intArray == null || intArray.length == 0) { return; } // 初始化头结点 head = new Node(intArray[0]); Node tmp = head; // 从第二个元素开始遍历挂载新节点 for (int i = 1; i < intArray.length; i++){ Node newNode = new Node(intArray[i]); tmp.setNext(newNode); tmp = newNode; } } public void printList(){ // 空链表判断 if(head == null) { System.out.println("链表为空"); return; } Node tmp = head; while (tmp.getNext() != null){ System.out.print(tmp.getValue() + " -> "); tmp = tmp.getNext(); } System.out.println(tmp.getValue()); System.out.println(); } }
功能验证参考
public class Test { public static void main(String[] args) { int[] arr = {2,4,6,8,10}; IntLinkedList list = new IntLinkedList(arr); list.printList(); // 输出结果:2 -> 4 -> 6 -> 8 -> 10 } }
内容的提问来源于stack exchange,提问作者huy_tran_2308
相关产品推荐
相关产品推荐

