Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jingz8804/9466275 to your computer and use it in GitHub Desktop.
Save jingz8804/9466275 to your computer and use it in GitHub Desktop.
import java.util.NoSuchElementException;
import java.util.Iterator;
public class LinkedListQueue<Item> implements Iterable<Item>{
private class Node{
Item item;
Node next;
}
private Node head; // head of the queue; we dequeue at the head
private Node tail; // tail of the queue; we add new node to the tail
private int count; // the number of element in the queue
public LinkedListQueue(){
head = tail = null;
count = 0;
}
public void enqueue(Item item){
Node n = new Node();
n.item = item;
n.next = null;
if (count == 0){
head = tail = n;
}else{
tail.next = n;
tail = n;
}
count++;
}
public Item dequeue(){
if (count == 0) throw new NoSuchElementException("The queue is already!");
Item item = head.item;
head = head.next;
count--;
if (count == 0) tail = null; // avoid loitering
return item;
}
public int size(){
return count;
}
public Iterator<Item> iterator(){
return new LinkedListIterator();
}
private LinkedListIterator() implements Iterator<Item>{
private Node current = head;
public boolean hasNext(){return current != null;}
public void remove() {throw new UnsupportedOperationException();}
public Item next() {
if (!hasNext()) throw new NoSuchElementException("Queue is empty!");
Item item = current.item;
current = current.next;
return item;
}
}
public String toString(){
// since we have an iterator implemented, we could use the foreach method instead
// use StringBuilder instead of concantenating the string
StringBuilder builder = new StringBuilder();
for(Item item: this){
builder.append(item);
builder.append(" ");
}
return builder.toString();
}
}
@jingz8804
Copy link
Author

For a LinkedListQueue, it should be head -> N2 ->N3 -> ..... -> tail -> null

A few place where we should add the generic type:
The outer class LinkedListQueue implements Iterable

The Iterator iterator() method

The inner class LinkedListIterator implements Iterator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment