Skip to content

Instantly share code, notes, and snippets.

@Bambina-zz
Created March 21, 2017 03:21
Show Gist options
  • Save Bambina-zz/34af35cba46d7a9c86468866be95b6cb to your computer and use it in GitHub Desktop.
Save Bambina-zz/34af35cba46d7a9c86468866be95b6cb to your computer and use it in GitHub Desktop.
Queueの実装
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;
// First In First Out
public class TestQueue {
@Test
public void testQueue(){
Queue<String> q = new Queue<String>();
q.enqueue("0");
q.enqueue("1");
assertEquals("0", q.dequeue());
}
@Test
public void testQueue2(){
Queue<String> q = new Queue<String>();
q.enqueue("0");
q.enqueue("1");
q.enqueue("2");
q.dequeue();
assertEquals(2, q.size());
}
}
class Queue<E> {
static class Node<E> {
E data;
Node<E> next = null;
}
Node<E> first, last;
void enqueue(E e){
Node<E> node = new Node<E>();
node.data = e;
if(first == null){
first = node;
last = first;
} else {
last.next = node;
last = node;
}
}
E dequeue(){
if(first == null){
return null;
}
E obj = first.data;
first = first.next;
return obj;
}
int size(){
if(first == null){
return 0;
}
int length = 1;
Node<E> node = first;
while(node.next != null){
length++;
node = node.next;
}
return length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment