Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Question 1 the provided information: Node class LinkedList class In class,

ID: 3859989 • Letter: J

Question

Java Question 1

the provided information:

Node class

LinkedList class

In class, we wrote an implementation for a Stack class using an ArrayList to store the underlying data. Write your own Stack class (Stack.java) that uses a LinkedList to store the underlying (String) data. Your implementation should have (at least) a constructor, a push method, a pop method, and a peek method. The LinkedList class you use should be based off of the version we wrote in class (i.e., not using a Java standard library version)

Explanation / Answer

PROGRAM CODE:

Stack.java

package stack;

public class Stack {

   //private linkedlist object to hold the data

   private LinkedList top;

  

   //constructor that takes linkedlist as input

   public Stack(LinkedList t) {

       top = t;

   }

  

   //default constructor

   public Stack() {

       top = new LinkedList();

   }

  

   //inserts data into the stack

   public void push(String data)

   {

       top.addToFront(data);

   }

  

   //return true if stack is empty, otherwise false

   public boolean isEmpty()

   {

       return top.isEmpty();

   }

  

   //removes the element from top of the stack

   public void pop()

   {

       top.removeFront();

   }

  

   //returns the top element in the stack

   public String peek()

   {

       if(!top.isEmpty())

           return top.getFrontData();

       else return null;

   }

  

   //returns the string representation of the stack

   @Override

   public String toString() {

       return top.toString();

   }

}

Tester.java

package stack;

public class StackTester {

   public static void main(String[] args) {

       Stack stack = new Stack();

       stack.push("Apple");

       stack.push("Mango");

       stack.push("Banana");

       System.out.println(stack);

       stack.push("Peach");

       System.out.println(stack);

       stack.pop();

       System.out.println(stack);

   }

}

OUTPUT:

[Banana --> Mango --> Apple --> ]

[Peach --> Banana --> Mango --> Apple --> ]

[Banana --> Mango --> Apple --> ]

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote