Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package io.phydesmith.stack;
- public class ArrayBoundedStack<T> implements StackInterface<T> {
- private T[] elements;
- private int topIndex;
- public ArrayBoundedStack(int bound) {
- this.elements = (T[]) new Object[bound];
- topIndex = -1;
- }
- public void push(T element) {
- topIndex++;
- this.elements[topIndex] = element;
- }
- public T popTop() {
- T element = top();
- pop();
- return element;
- }
- public void popSome(int i) {
- for (int c = 0; c < i; c++) {
- pop();
- }
- }
- public void pop() {
- if (isEmpty()) {
- throw new StackUnderflowException("Pop attempted on empty stack");
- } else {
- this.elements[topIndex] = null;
- topIndex--;
- }
- }
- public T top() {
- T topOfStack = null;
- if (isEmpty()) {
- throw new StackUnderflowException("Top attempted on empty stack");
- } else {
- topOfStack = this.elements[topIndex];
- }
- return topOfStack;
- }
- public boolean swapStart() {
- if (topIndex <= 0) {
- return false;
- } else {
- T firstElement = this.elements[topIndex];
- T secondElement = this.elements[ topIndex-1 ];
- popSome(2);
- push(firstElement);
- push(secondElement);
- return true;
- }
- }
- public boolean isEmpty() {
- if (topIndex == -1) {
- return true;
- } else {
- return false;
- }
- };
- public boolean isFull() {
- if (topIndex == this.elements.length-1 ) {
- return true;
- } else {
- return false;
- }
- }
- public int size() {
- return this.topIndex+1;
- }
- public String toString() {
- String elements = "";
- for (int i = this.elements.length-1; i >= 0; i--) {
- elements += "\n" + (i+1) + ") " + this.elements[i];
- }
- return elements;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement