Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions Arrays/Arraystack
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
public class Arraystack<E> implements Stack<E>
{
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<Integer> 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
}
}