Last active
August 29, 2015 14:02
-
-
Save agungsijawir/6f546d0bef99b409add2 to your computer and use it in GitHub Desktop.
Implementation of Queue with Array (Java)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ArrayQueue1 implements Queue { | |
private static Object [] arr; | |
private static int currentSize; | |
private static int front; | |
private static int back; | |
private static final int DEFAULT_CAPACITY = 10; | |
public ArrayQueue1() | |
{ | |
arr = new Object[ DEFAULT_CAPACITY ]; | |
makeEmpty( ); | |
} | |
public void enqueue(Object x) { | |
if( currentSize == arr.length ) // jika besaran entry data melebihi kapasitas | |
doubleQueue( ); // buat array yang baru dengan memperbesar kapasitas 2x | |
back++; | |
arr[back] = x; | |
currentSize++; | |
} | |
public Object getFront() { | |
if(isEmpty()) throw new UnderflowException("Array Underflow!"); | |
return arr[front]; | |
} | |
public Object dequeue() { | |
if(isEmpty()) throw new UnderflowException( "ArrayQueue dequeue" ); | |
currentSize--; | |
Object returnValue = arr[front]; | |
front++; | |
return returnValue; | |
} | |
public boolean isEmpty() { | |
return currentSize == 0; | |
} | |
public void makeEmpty() { | |
currentSize = 0; | |
front = 0; | |
back = -1; | |
} | |
private void doubleQueue( ) { | |
Object [] arrBaru; | |
arrBaru = new Object[ arr.length * 2 ]; | |
for( int i = 0; i < currentSize; i++, front++ ) | |
arrBaru[ i ] = arr[ front ]; | |
arr = arrBaru; | |
front = 0; | |
back = currentSize - 1; | |
} | |
public static void display() { | |
if (back > front) { | |
System.out.println(">> Elemen di antrian:"); | |
for (int i = front; i <= back; i++) System.out.println(arr[i]); | |
} | |
} | |
public static void main(String[] args) { | |
ArrayQueue1 q = new ArrayQueue1( ); | |
try { | |
q.enqueue(1); display(); | |
q.enqueue(2); display(); | |
q.enqueue(3); display(); | |
q.enqueue(4); display(); | |
q.dequeue(); display(); // remove 1st element from list | |
q.enqueue(5); display(); | |
q.enqueue(6); display(); | |
q.dequeue(); display(); // remove 2nd element from list | |
} | |
catch( UnderflowException e ) { System.out.println( "Unexpected overflow" ); } | |
System.out.println("Final result:"); | |
while( !q.isEmpty() ) | |
System.out.println( q.dequeue() ); | |
} | |
} | |
interface Queue { | |
void enqueue(Object x); | |
Object getFront(); | |
Object dequeue(); | |
boolean isEmpty(); | |
void makeEmpty(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment