GTestQueue.java
Select all
/* GTestQueue.java Dave Klick 2014-03-26 Queue implementation that accepts any type of object. */ class Queue
{ private class Node
{ T data; Node
next; public Node(T obj) { data = obj; next = null; } public Node(Node
n) { data = n.data; next = null; } } private Node
head = null; private Node
tail = null; private int count = 0; public void add(T obj) { Node
newnode = new Node
(obj); if (tail == null) { head = tail = newnode; } else { tail.next = newnode; tail = newnode; } count++; } public boolean isEmpty() { return head==null; } public int length() { return count; } public int size() { return count; } public T peek() { if (head == null) return null; else return head.data; } public T remove() { if (head == null) return null; else { T data = head.data; head = head.next; if (head == null) tail = null; count--; return data; } } public void clear() { while (!isEmpty()) remove(); } public String toString() { StringBuilder s = new StringBuilder(); Node
cur = head; while (cur != null) { if (s.length() > 0) s.append(", "); s.append(cur.data.toString()); cur = cur.next; } return s.toString(); } } public class GTestQueue { public static void main(String[] args) { Queue
q = new Queue
(); q.add(new String("Item 1")); q.add(new String("Item 2")); q.add(new String("Item 3")); q.add(new String("Item 4")); System.out.println(q); System.out.println(q.length()); System.out.println(q.peek()); while (!q.isEmpty()) { System.out.println("Removed: " + q.remove()); } System.out.println(q.length()); } }