In: Computer Science
I've already worked on isEmpty, so please check that and solve the other parts to the question as well. Will rate as soon an I see that it is answered.
In this section, you will implement a generic Stack
class implemented using linked list. Assume the linked list node
class is already defined as below:
public class LLNode<T> {
public LLNode<T> link;
public T info;
public LLNode(T in) { info = in; link = null; }
}
Note that both class variables are public so any outside class can access them directly. Also assume that class StackUnderflowException has been defined that inherits Java’s Exception class. Your task is to implement four methods in the generic class LinkedListStack<T>.
public class LinkedListStack<T> {
private LLNode<T> head; // head of linked list, also stack top pointer
public LinkedListStack() { head = null; } // constructor
public boolean isEmpty() { // [1 pts]
// TODO: return true if stack is empty, false otherwise
// NO MORE THAN 1 LINE OF CODE!
if(head.link == null) return true;
}
public void push(T element) { // [2 pts]
// TODO: push an element to the stack
// NO MORE THAN 3 LINES of CODE!
}
public T peek() throws StackUnderflowException { // [2 pts]
// TODO: return the top element of the stack (but do
NOT
// remove it). NO MORE THAN 4 LINES of CODE!
}
public T pop() throws StackUnderflowException { // [3 pts]
// TODO: remove and return the top element of the stack
// It throws StackUnderflowException if stack is empty
// NO MORE THAN 6 LINES of CODE!
}
public class LinkedListStack<T> {
private LLNode<T> head; // head of linked list, also stack top pointer
public LinkedListStack() { head = null; } // constructor
public boolean isEmpty() { // [1 pts]
return (head==null); // RETURNS TRUE IF LIST
EMPTY
}
public void push(T element) { // [2 pts]
LLNode<T> p = new LLNode<T>(element);//
create node
if(isEmpty()){ // check stack is empty
head = p; // assign head is first
node
}else{
p.link = head;
head = p;
}
}
public T peek() throws StackUnderflowException { // [2
pts]
if (head == null) {
throw new StackUnderFlowException("The stack is empty.");
}
return head.info;
}
public T pop() throws StackUnderflowException { // [3 pts]
if (head == null) {
throw new StackUnderflowException("The stack is empty.");
}
T output = head.info;
head = head.link;
return output;
}
/* PLEASE UPVOTE */