I’ve written this program to implement a LinkedList. There are 2 classes: Node
and IntLinkedList
and the relationship between them is aggregation. In the IntLinkedList
class, the constructor’s parameter is an array and I’ve tried to use a for-each loop to add the data of the array to the linked list. Here is my code:
Node.java
JavaScript
x
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
JavaScript
import java.lang.*;
import java.util.*;
public class IntLinkedList {
private Node head;
public IntLinkedList(){
this.head = null;
}
public IntLinkedList(int[] intArray){
Node tmp = head;
for (int data : intArray){
while (tmp.getNext() != null){
tmp.setValue(data);
tmp = tmp.getNext();
}
}
}
public void printList(){
Node tmp = head;
while (tmp.getNext() != null){
System.out.println(tmp.getValue() + " -> ");
tmp = tmp.getNext();
}
System.out.println(tmp.getValue());
System.out.println();
}
}
I’ve tried for many times but it still didn’t work.
Advertisement
Answer
In your code tmp
is always null
, so that when you call tmp.getNext()
you will get NPE
forever.
JavaScript
public class IntLinkedList {
private Node head;
public IntLinkedList() {
this.head = null;
}
public IntLinkedList(int[] intArray) {
this();
Node tmp = head;
for (int data : intArray) {
if (head == null) {
head = new Node(data);
tmp = head;
} else {
tmp.setNext(new Node(data));
tmp = tmp.getNext();
}
}
}
public void printList() {
Node tmp = head;
while (tmp != null) {
System.out.println(tmp.getValue() + " -> ");
tmp = tmp.getNext();
}
System.out.println();
}
}