kusur
kusur

Reputation: 618

Pop operation of stack implementation not working as expected

I am JAVA n00b. I am trying to implement a stack data structure in Java. The algorithms of push, peek and display are working fine. The pop algorithm is not working as expected:

public int pop() {
    int temp;
    if(isEmpty())
        return -1;
    else {
        temp = arr[topElem];
        topElem--; // points to the top most element in the stack
        count--;   // keeps track of the total number of elements in the stack
        return temp;
    }
}

The case in switch statement for this algorithm is as follows:-

case 2:
    if(st.pop()==-1)
        System.out.println("The stack is empty.");
    else
        System.out.printf("The element popped is %d\n",st.pop());
    break;

If the elements entered are ( in that order ):- 1 2 4 Then at the first call to pop, 2 is popped and then only 1 remains in the stack. I am able to understand what might be wrong but can't pinpoint it in the code.

Upvotes: 0

Views: 316

Answers (2)

Rollen Holt
Rollen Holt

Reputation: 517

you're calling pop twice.

the first is:

if(st.pop()==-1)
       System.out.println("The stack is empty.");

and the second is :

System.out.printf("The element popped is %d\n",st.pop());

you can use a variable to store the value of st.pop() and then check the value of the variable. next to write some logic code.

Upvotes: 0

Bernhard Barker
Bernhard Barker

Reputation: 55609

The problem is that you're calling pop twice (once in st.pop() == -1, and once in the printf).

You should change your code to something like:

int value = st.pop();
if (value == -1)
   System.out.println("The stack is empty.");
else
   System.out.printf("The element popped is %d\n", value);

Upvotes: 3

Related Questions