For one of my classes we just began using IntLinkedStacks, and I need to add a size() method that will count the size of my list. So, I began by creating an instance variable to define size, and then began coding. However, in my program, I keep getting a Null Exception Error. I read up what this error means, but could someone clarify what it means within this code, and why I am getting this error?
import java.util.EmptyStackException;
public class IntLinkedStack implements IntStack {
private Node top;
private int size;
public void push(int item) {
top = new Node(item, top);
}
public int pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
int value = top.data;
top = top.next;
return value;
}
public boolean isEmpty() {
return top == null;
// return (size() == 0);
}
public int peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return top.data;
}
public int size() {
for(Node n = top; n.next != null; n = n.next)
size ++;
return size;
}
private static class Node {
private int data;
private Node next;
private Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
public static void main(String[] args) {
IntStack s = new IntLinkedStack();
System.out.println("Size: " + s.size());
for (int i = 0; i < 5; i++) {
s.push(i*i);
}
System.out.println("Size: " + s.size());
while (!s.isEmpty()) {
System.out.print(s.pop() + " ");
}
System.out.println();
System.out.println("Size: " + s.size());
}
}