Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

class StackList implements StackInterface { / / Note: Stack follows the LIFO ( Last In First Out ) principle. private Node top; private int

class StackList implements StackInterface {
// Note: Stack follows the LIFO ("Last In First Out") principle.
private Node top;
private int size;
// add item on top
// O(1)
public void push(T item){
// save the prev. top/node in a temp variable
Node prev = top;
// init. top to a new node and pass in the item and prev. node
top = new Node(item, prev);
// increment size
size++;
}
// remove item on top and returns it back to the user/caller
// O(1)
public T pop(){
if(top == null){// OR size ==0
System.out.println("unable to pop, stack is empty");
return null;
}
// save the item that will be returned back to the caller
T itemOnTop = top.getItem();
// remove the item on top
top = top.getNext();
// decrement size
size--;
// return item that was on top
return itemOnTop;
}
// without popping, return item on top of the stack
// O(1)
public T peek(){ return null; }
// O(1)
public boolean isEmpty(){ return false; }
// O(1)
public int size(){ return 0; }
// O(N)
public boolean contains(T item){ return false; }
}Convert StackList from "Week -05" to use Arrays instead of Nodes, call it: StackArray.java
Unlike Nodes, arrays have a hard capacity which needs to be taken into account when implementing this data structure
A Stack follows the LIFO (Last In First Out) principle, which means items are added (pushed) at the "top" of the data structure and removed (popped) from the "top"
In an array, "top" would the the last item in the array that is not null
HINT: One can use an integer variable to keep track (bookkeeping) of the index that is considered the "top" most item in the Stack array

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions

Question

C) and for AF? Pg45

Answered: 1 week ago