diff --git a/Arrays/Arraystack b/Arrays/Arraystack new file mode 100644 index 0000000..bcdc084 --- /dev/null +++ b/Arrays/Arraystack @@ -0,0 +1,80 @@ +public class Arraystack implements Stack +{ + public static final int CAPACITY=1000; + private E[] data; + private int t = -1; + + public Arraystack() + { + data= (E[]) new Object[CAPACITY]; + } + + public Arraystack(int capacity) { + data= (E[]) new Object[capacity]; + } + + @Override + public int size() { return t+1; } + + @Override + public boolean isEmpty() { return t==-1; } + + @Override + public void push(E e) throws IllegalStateException { + t++; + data[t]=e; + + } + + @Override + public E top() { + if(isEmpty()) + return null; + return data[0]; + } + + @Override + public E pop() { + if(isEmpty()) + { + System.out.println("OVERFLOW"); + return null; + } + E d=data[t]; + t--; + return d; + } + + public String toString() { + StringBuilder sb = new StringBuilder("("); + for(int i=0;i<=t;i++) + { + sb.append(data[i]); + sb.append(", "); + + } + sb.append(")"); + return sb.toString(); + + } + public static void main(String[] args) { + Stack S = new Arraystack<>(); + S.push(5); // contents: (5) + S.push(3); // contents: (5, 3) + System.out.println(S.size()); // contents: (5, 3) outputs 2 + System.out.println(S.pop()); // contents: (5) outputs 3 + System.out.println(S.isEmpty()); // contents: (5) outputs false + System.out.println(S.pop()); // contents: () outputs 5 + System.out.println(S.isEmpty()); // contents: () outputs true + System.out.println(S.pop()); // contents: () outputs null + S.push(7); // contents: (7) + S.push(9); // contents: (7, 9) + System.out.println(S.top()); // contents: (7, 9) outputs 9 + S.push(4); // contents: (7, 9, 4) + System.out.println(S.size()); // contents: (7, 9, 4) outputs 3 + System.out.println(S.pop()); // contents: (7, 9) outputs 4 + S.push(6); // contents: (7, 9, 6) + S.push(8); // contents: (7, 9, 6, 8) + System.out.println(S.pop()); // contents: (7, 9, 6) outputs 8 + } +}