Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Stack<T> {
- //Constructor
- Stack() {
- }
- //String[] stackArray = new String[6]; //Array used for stack
- T[] stackArray = (T[]) new Object[6]; //Switched to Generic coding array type-casted to T[]
- int stackPointer = -1; //Starts at -1 to show stack is empty
- //Follows array index 0 being something is there
- //Prints the stack
- public void printStack() {
- for (int i = 0; i < stackArray.length; i++) {
- if (i == 0 && stackArray[i] == null) { //Checks if stack is empty
- System.out.println("Stack is empty - Print Stack Function");
- break; //Break out of the for loop
- }
- else if (stackArray[i] == null ) { //Checks null values
- //Do nothing
- }
- else {
- System.out.println(stackArray[i]); //Displays if not null
- }
- }
- }
- //Pushes an item onto the stack
- public void push(T item) {
- // only proceed if the stack is not full
- if ( stackPointer < (stackArray.length - 1) ) {
- stackArray[stackPointer + 1] = item; //Push the item onto the stack
- stackPointer++; //Increment the stack pointer
- } else {
- System.out.println("Stack is full - Push Function"); //Print stack full message
- }
- }
- //Takes the last item out of the stack
- public T pop() {
- T item; //The item to be returned by the pop method
- if (stackPointer >= 0) { //Only proceed if the stack is not empty
- item = stackArray[stackPointer];
- stackArray[stackPointer] = null;
- stackPointer--;
- return item;
- }
- else {
- System.out.println("Stack is empty - Pop Function"); //Print empty stack method
- item = null;
- return item;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement