0

I am trying to implement stack but pop() in not working properly. The last element after popping doesn't get deleted and stack does not get empty. I have checked the head at last does not points to null which is causing the problem. I am not able to find why this is happening can anyone please explain.

public class StackUsingLL {

public class Node{
    int data;
    Node next;
    
    Node(int data){
        this.data=data;
    }
}

Node head;

boolean isEmpty() {
    if(head==null)return true;
    return false;
}

void push(int x) {
    Node newNode= new Node(x);
    if(head==null) {
        head=newNode;
    }
    newNode.next=head;
    head=newNode;
    
}

int pop() {
    if(head==null) {
        System.out.println("Stack is empty");
        return 0;
    }else {
        int popped=head.data;
        head= head.next;
        return popped;
    }
    
    
}

int peek() {
    if(head==null) {
        System.out.println("Stack empty");
        return 0;
    }
    return head.data;
}

public static void main(String[] args) {
    StackUsingLL sll= new StackUsingLL();
    
    sll.push(10);
    sll.push(20);
    sll.push(30);
    System.out.println(sll.pop()+" popped");
    System.out.println(sll.pop()+" popped");
    System.out.println(sll.pop()+" popped");
    
    System.out.println(sll.isEmpty());
    System.out.println("at top: "+sll.peek());
    
}

}

2 Answers 2

2

The issue is in push. When the list is empty you assign head twice:

void push(int x) {
    Node newNode = new Node(x);
    if (head == null) {
        head = newNode;
        return;  // <<--- Add this so it doesn't get assigned in the following lines.
    }
    newNode.next = head;
    head = newNode; 
}

Without the return you end up with head.next = head.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you, i understand now where was the mistake.
0

I recommend that just don't change the reference head but also delete it . By just changing the reference , prev Node is still intact

int pop() {
    if(head==null) {
        System.out.println("Stack is empty");
        return 0;
    }
        Node popped=head;
             head=head.next;
          popped.next=null;
        
        return popped.data;
    
    
    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.