Skip to content

Instantly share code, notes, and snippets.

@agungsijawir
Last active August 29, 2015 14:02
Show Gist options
  • Save agungsijawir/71aa4bcc27bae1c05c19 to your computer and use it in GitHub Desktop.
Save agungsijawir/71aa4bcc27bae1c05c19 to your computer and use it in GitHub Desktop.
package StackQueueAlgo;
public class ArrayStack implements Stack {
public static final int CAPACITY = 10;
private static int _capacity;
private static Object _S[];
private static int _top = -1;
public ArrayStack() {
this(CAPACITY);
}
public ArrayStack(int cap) {
_capacity = cap;
_S = new Object[_capacity];
}
public int size() {
return (_top + 1);
}
public boolean isEmpty() {
return (_top < 0);
}
public Object top() {
try {
if (isEmpty())
throw new StackKosongException("Stack is empty.");
} catch (Exception e) {
e.printStackTrace();
}
return _S[_top];
}
public void push(Object element) {
if (size() == _capacity) {
try {
throw new StackPenuhException("Stack overflow.");
} catch (Exception e) {
e.printStackTrace();
}
}
_S[++_top] = element;
}
public Object pop() {
Object elem = null;
try {
if (isEmpty())
throw new StackKosongException("Stack is empty.");
elem = _S[_top];
_S[_top--] = null;
} catch (Exception e) {
e.printStackTrace();
}
return elem;
}
public static void display() {
if (_top > _capacity) {
System.out.println(">> Elemen di antrian:");
for (int i = _top; i <= _capacity; i++)
System.out.println(_S[i]);
}
}
/* demo goes here */
public static void main(String[] args) {
ArrayStack q = new ArrayStack( );
try {
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.pop(); // remove 1st element from stack
q.push(5);
q.push(6);
q.pop(); // remove 2nd element from stack
}
catch( UnderflowException e ) { System.out.println( "Unexpected overflow" ); }
System.out.println("Final result:");
while( !q.isEmpty() )
System.out.println( q.pop() );
}
}
interface Stack {
public int size(); // return: num of elements in the stack
public boolean isEmpty(); // return: true, if stack is empty. otherwise false
public Object top()
throws StackKosongException; // return: top element in the stack
public void push (Object element); // push an element to stack
public Object pop()
throws StackKosongException; // return and remove top element in the stack
}
@SuppressWarnings("serial")
class StackKosongException extends RuntimeException {
public StackKosongException( String message )
{
super( message );
}
}
@SuppressWarnings("serial")
class StackPenuhException extends RuntimeException {
public StackPenuhException ( String message ) {
super ( message );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment