Question: This is a Stack class by using Linked list. I push the new data at the tail, so I pop at the tail too. However,

This is a Stack class by using Linked list. I push the new data at the tail, so I pop at the tail too. However, there are something wrong for the pop method. I push "R","a","c","e","c","a", and "r", but I cannot pop out the very last Node "R". How to fix it?

public class Stack { private class Node{ private T data; private Node link; public Node(){ data = null; link = null; } public Node(T input, Node next){ data = input; link = next; } } private Node head; public Stack(){ head = null; } public void push(T input){ if (head==null){ head = new Node(input, null); } else{ Node position = head; while (position.link!=null){//stop at last node position = position.link; } Node a = new Node(input, null); position.link = a; } } public T pop(){ Node removed = new Node(); Node position = head; int count=1; int length = size(); while (count a = new Stack(); // Queue q = new LinkedList(); a.push('R'); a.push('a'); a.push('c'); a.push('e'); a.push('c'); a.push('a'); a.push('r'); System.out.println("Size : " + a.size()); a.outputList(); while(!a.isEmpty()) { System.out.println(a.pop()); } }

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!