Note that there are some explanatory texts on larger screens.

plurals
  1. POSimple Stack Implementation in Java not working
    text
    copied!<p>I have implemented a very basic Stack in Java which is giving strange errors never faced before. The code is as follows:</p> <pre><code>public class Stack { Node top; int size; public Stack() {top=null; size=0;} public int pop() { if(top!=null) { int item = top.data; top = top.next; size--; return item; } return -1; } public void push(int data) { Node t = new Node(data); t.next = this.top; this.top = t; size++; } public boolean isEmpty() { return size&lt;=0 ; } public int getSize() { return size; } public int peek() { return top.data; } public void printStack() { Node n = this.top; int pos = this.getSize(); while(pos&gt;=0) { System.out.println("Position: " + pos + " Element: " + n.data); if(pos&gt;0) { n = n.next; } pos--; } } } class Node { public int data; public Node next; Node(int d) {data=d; next=null;} public int getData() {return data;} } class Tester { public static void main(String[] args) { Stack s = new Stack(); s.push(9);s.push(2);s.push(7);s.push(3);s.push(6);s.push(4);s.push(5); System.out.println("Size is: " + s.getSize()); //s.printStack(); for (int i=0; i&lt;s.getSize(); i++) { System.out.print(s.pop()+ " "); } System.out.println(); } } </code></pre> <p>I have tested thoroughly and found that the push operation works perfectly with all the 7 elements being pushed in the correct sequence with proper next/top pointer set. But, when I try to pop out all the elements, then only it pops the top-4 (5-4-6-3) leaving the other ones. Then, I tried to perform a printStack with the above method and there it gives random NullPointerException errors as follows: </p> <pre><code>run: Position: 7 Element: 5 Position: 6 Element: 4 Position: 5 Element: 6 Position: 4 Element: 3 Exception in thread "main" java.lang.NullPointerException Position: 3 Element: 7 Position: 2 Element: 2 at Stack.printStack(Stack.java:58) Position: 1 Element: 9 at Tester.main(Stack.java:95) Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds) </code></pre> <p>These errors doesn't make sense to me and moreover by introducing some more print statements in push() and printStack() for tracing it starts to throw more random exceptions. The errors are completely non-deterministic for each run and gives different patterns in different machines. I have traced one complete run with Netbeans debugger and found no errors!</p> <p>Your help is highly appreciated! Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload