Reputation: 1
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());
}
}
Upvotes: 0
Views: 1481
Reputation: 13533
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
.
Upvotes: 2
Reputation: 184
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;
}
Upvotes: 0