1 Problem 1 Implement a stack, You do not need to actually extend an interface I
ID: 3813278 • Letter: 1
Question
1Problem 1
Implement a stack, You do not need to actually extend an interface I simply want you to implement a stack. I have given you a starter below:
public class Stack<T>
{
//You will need to have some sort of private variables to store the stack itself here.
//If you use a linked implementation include the node in the submission.
public Stack()
{
//Fill in your code here.
}
public void pop()
{
//Fill in your code here.
}
public T top()
{
//Fill in your code here.
}
public void push(T element)
{
//Fill in your code here.
}
//You are welcome to add any other private functions.
}
Explanation / Answer
Stack.java
public class Stack<T> {
private T [ ] theArray;
private int topOfStack;
private static final int DEFAULT_CAPACITY = 10;
public Stack( ) {
theArray = (T[])new Object[DEFAULT_CAPACITY];
}
public T top( ) throws Exception
{
if( isEmpty( ) )
throw new Exception( "ArrayStack top" );
return theArray[ topOfStack ];
}
/**
* Remove the most recently inserted item from the stack.
* @throws Exception
* @throws UnderflowException if the stack is empty.
*/
public void pop( ) throws Exception {
if( isEmpty( ) )
throw new Exception( "ArrayStack pop" );
topOfStack--;
}
/**
* Insert a new item into the stack.
* @param x the item to insert.
*/
public void push( T x )
{
theArray[ ++topOfStack ] = x;
}
/**
* Test if the stack is logically empty.
* @return true if empty, false otherwise.
*/
private boolean isEmpty( )
{
return topOfStack == -1;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.