Skip to content

Instantly share code, notes, and snippets.

@simonjohn027
Created February 2, 2019 05:55
Show Gist options
  • Save simonjohn027/5d21e492a68e929b414706b76f08d4f1 to your computer and use it in GitHub Desktop.
Save simonjohn027/5d21e492a68e929b414706b76f08d4f1 to your computer and use it in GitHub Desktop.
Generic Stack Implementation using arrays
//This is the data Structure that follows the LIFO
// Stack is the linear Data structure in which add and remove operation
//can only be done on one end following LIFO principle.
//Can be implemented using Arrays or LinkedList
/*This data Structure(Stack) extends the Vector Class which implemented *
*the following interfaces:
* 1. List which extends 2. Collection which extends Iterators
*
* The main methods in Stack ADT are:
* 1. Object pop == remove the top stack
* 2. Object push == add the stack at the top of the stack
* 3. Object peek == which check what element is at the top of the stack
* 4. Boolean isEmpty == which return boolean of whether is empty or not
* 5. int search = for (1) is there is element (-1) if there is no element
*/
//Interface for Stack: Define all the required methods
interface StackADT <T> {
//public void create(); This wont be need as we can do with the class constructor
//Depend on the data type used under the hood this can run up 0(n).
public <T> T pop();
public void push( T t);
public <T> T peek();
public boolean isEmpty();
public boolean isFull();
}
//Impementation of Stack Using Arrays
public class Stacks <T> implements StackADT {
//Declaration of the Data Type to be used
private T [ ] data;
private int capacity = 30;
private int stackTop;
//Constuction of Stack using Stack constructor
public Stacks(T []t){
data = t;
stackTop = -1;
}
public void push( T t){
if(stackTop+1 == data.length){
System.out.println("Stack is Full You can't add more data");
}
else{
data[++stackTop] = t;
}
}
public T pop(){
T poped = data[stackTop];
data[stackTop] = null; //Just make it 0(1)
stackTop--;
return poped;
}
public T peek(){
return data[stackTop];
}
public boolean isEmpty(){
return stackTop == -1 ? true:false;
}
public boolean isFull(){
return stackTop+1 == data.length ? true : false;
}
public static void main(String[] args) {
String [] ary = {""};
Stacks Name = new Stacks <String>(ary);
Name.push("Simon");
Name.push("Alex");
Name.push("Abel");
System.out.println(Name.isEmpty());
System.out.println(Name.isFull());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment