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

PLEASE MAKE SURE TO COMMENT THROUGH THE CODE SO I CAN GIVE YOU 5 STARS!! Write a

ID: 3569328 • Letter: P

Question

PLEASE MAKE SURE TO COMMENT THROUGH THE CODE SO I CAN GIVE YOU 5 STARS!!

Write a generic class that creates an instance of a stack data structure. This is a last in first out (LIFO) data structure. This means information put into it at the beginning can only be accessed at the end. Here's a picture:

First download the Lab22Files

Put the driver in your project

DO NOT ALTER THE DRIVER!

Write a class file called GenericStack that can be compose of generic types.

Write an interior class called StackNode

This means it is a private class within Stack

Attributes of this interior class will be

Data

Explanation / Answer

Here you go :)

Comment if you have any doubts

//GenericStack class

import java.util.ArrayList;

public class GenericStack<T>
{
   class StackNode
   {
       private T data;
       private StackNode link;
      

//default constructor
       public StackNode()
       {

//initializing the data and link variables
           this.data=null;
           this.link=null;
       }
   }
  
   private StackNode head,current;
  
   public GenericStack()
   {

//initializing head and current variables
       this.head=null;
       this.current=null;
   }
  

//adding new node
   public void push(T data)
   {
       StackNode n=new StackNode();//creating new node object
       n.data=data;//setting data of new node
       n.link=this.head;//linking the nextnode to head node
       this.head=n;//setting the head to the new node
       this.current=this.head;
   }
  
   public T pop()
   {
       T t=this.head.data;//storing the head data in a temporary variable
       this.head=this.head.link;//removing the link from head node to second node
       this.current=this.head;//making the second node the head node
       return t;
   }
   public void printStack()
   {
       GenericStack<T> dum=this;
       while(dum.current!=null)
       {
           System.out.println(dum.current.data);
           dum.current=dum.current.link;
       }
   }
  
   public boolean canPop()
   {
       if(this.head!=null)return true;//if the head is null it means no elements
       return false;
   }
  
   public void addArrayList(ArrayList<T> al)
   {
       for(int i=0;i<al.size();i++)
       {
           this.push(al.get(i));//pushing the al elements to the stack
       }
   }
}

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