Created
March 22, 2016 08:03
-
-
Save mchayapol/0de36310d95bdb98bd73 to your computer and use it in GitHub Desktop.
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
package u5715111.adt.queue; | |
import java.util.Arrays; | |
public class Queue { | |
int head; | |
int tail; | |
int data[]; | |
public Queue(int size) { | |
head = 0; | |
tail = 0; | |
data = new int[size]; | |
} | |
public boolean isEmpty() { | |
return head == tail; | |
} | |
public void enqueue(int newData) { | |
if (tail == data.length) { | |
// you can't add | |
throw new ArrayIndexOutOfBoundsException("Queue is full"); | |
} | |
data[tail] = newData; | |
tail++; | |
} | |
@Override | |
public String toString() { | |
StringBuffer sb = new StringBuffer("["); | |
for(int i=head; i<tail; i++) { | |
sb.append(data[i]); | |
sb.append(' '); | |
} | |
sb.deleteCharAt(sb.length()-1); | |
sb.append("]"); | |
return sb.toString(); | |
} | |
public int size() { | |
return tail-head; | |
} | |
public int dequeue() { | |
return data[head++]; | |
} | |
} |
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
package u5715111.adt.queue; | |
import static org.junit.Assert.*; | |
import org.junit.Test; | |
public class QueueTest { | |
@Test | |
public void test() { | |
Queue q = new Queue(10); | |
assertEquals(true, q.isEmpty()); | |
q.enqueue(5); q.enqueue(3); | |
q.enqueue(2); q.enqueue(10); | |
System.out.println( q.toString() ); | |
assertEquals("[5 3 2 10]" , q.toString()); | |
assertEquals(false, q.isEmpty()); | |
assertEquals(4, q.size()); | |
assertEquals(5, q.dequeue()); | |
assertEquals(3, q.dequeue()); | |
assertEquals(2, q.dequeue()); | |
assertEquals(10, q.dequeue()); | |
assertEquals(true, q.isEmpty()); | |
assertEquals(0, q.size()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment