Design and implement a class Stack that supports stacks that are implemented usi
ID: 3773335 • Letter: D
Question
Design and implement a class Stack that supports stacks that are implemented using a linked-list.
TestLinkList.java which is below can be modified to provide the linked-list functionality. If this code is not used, then you are required to implement your own linked-list code.
The implementation of class Stack is not allowed use arrays, ArrayList, of Vectorobjects. In other words, it must be implemented using a linked-list.
class Stack must support the following instance methods.
You must define a class StackEmptyException that extends class Exception.
The linked-list does not have any maximum capacity for class Stack objects.
The main() method of your program should contain code to test class Stackobjects. This program can use your Menu and MenuItem classes.
TestLinkList.java
Explanation / Answer
I am using the Link List code provided by you. :)
Stack using Linked List:
class LLIndex {
public LLNode head; //points to the front of the list
public LLNode tail; //points to the rear of the list
public LLNode current; //this is the cursor
public LLIndex() {}
}
class LLNode {
public String token;
public LLNode next;
public LLNode prev;
public LLNode(String token) { this.token = token; }
}
class Stack
{
public void push(Object elem) {
String element=elem;
addNode(element); // From your LL class
}
public Object pop() throws StackEmptyException {
deleteNode(); // From your LL class
}
public Object top() throws StackEmptyException {
if (list.current == null) return null; //empty list
else
{
while(list.current->next!=null)
list.current=list.current->next;
return list.current;
}
}
public Object print() throws StackEmptyException {
printBackwards();
// or printForwards..(depending on how you want to print it :)
}
public static void main(String args[])
{
int ch;
System.out.println("Enter your choice");
System.out.println(" 1 - Push");
System.out.println(" 2 - Pop");
System.out.println(" 3 - Top");
System.out.println(" 4 - Empty");
System.out.println(" 5 - Exit");
System.out.println(" 6 - Display");
Scanner in=new Scanner(System.in);
ch=in.nextInt();
// Now based on the number of choice.. Perform your action :)
}
}
class StackEmptyException extends Exception()
{
public StackEmptyException(String message)
{
super(message);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.