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

Objective: Using Java, write a generic class that creates an instance of a stack

ID: 3816348 • Letter: O

Question

Objective: Using Java, write a generic class that creates an instance of a stack data structure using a linked list (NOT an array). 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. Picture included below
Write a class file called IntStack 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 – this is the data of the integer type Next – a link to the next node Create the following constructors for this interior type: A default constructor that sets everything to null A constructor where it has parameters for the data and the next link Back to GenericStack Attributes of this class are Head – an instance of the StackNode that always keeps track of the top of the list Create the following constructors Default – sets both head and current to null Create the following Methods Push – this takes in integer data and then creates a new instance of the stack node and then pushes it on as the new head Pop – this returns the integer value of the current head and then removes it from the list by resetting the head to the head’s next link canPop – this returns true if the head is not null printStack – this iterates through the stack printing the data values of each item in the stack Finally write a class that demonstrates that all the stack functionality works.
YOU MUST COMMENT YOUR CODE Push T Pop

Explanation / Answer

public class StackLinkedList<T> implements Stack<T> {
private int total;
private Node first;
private class Node {
private T ele;
private Node next;
}
public StackLinkedList() { }
public StackLinkedList<T> push(T ele)
{
Node current = first;
first = new Node();
first.ele = ele;
first.next = current;
total++;
return this;
}
public T pop()
{
if (first == null) new java.util.NoSuchElementException();
T ele = first.ele;
first = first.next;
total--;
return ele;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
Node tmp = first;
while (tmp != null) {
sb.append(tmp.ele).append(", ");
tmp = tmp.next;
}
return sb.toString();
}

}