public class LinkedQueue<Item> extends java.lang.Object implements java.lang.Iterable<Item>
This implementation uses a singly-linked list
with a non-static nested class
for linked-list nodes. See Queue
for a version that uses a static nested class.
The enqueue, dequeue, peek, size, and is-empty
operations all take constant time in the worst case.
For additional documentation, see Section 1.3 (p.121 and p.151) of "Algorithms, 4th Edition," by Robert Sedgewick and Kevin Wayne.
(In the textbook, this class is called Queue. On the booksite, the class Queue differs from the present LinkedQueue class because it uses a static class to define Node.)
Classes used from algs4/cslib library: String StringBuilder, StdIn, StdOut (the last two only in main()). Class used from java.util library: Iterator.
Constructor and Description |
---|
LinkedQueue()
Creates an empty queue.
|
Modifier and Type | Method and Description |
---|---|
Item |
dequeue()
Removes and returns the item on this queue
that was least recently added.
|
void |
enqueue(Item item)
Adds the item to this queue.
|
boolean |
isEmpty()
Is this queue empty?
|
java.util.Iterator<Item> |
iterator()
Returns an iterator that iterates over the items in this queue
in FIFO order.
|
static void |
main(java.lang.String[] args)
Unit test facility.
|
Item |
peek()
Returns the item least recently added to this queue
but does not remove the item.
|
int |
size()
Returns the number of items in this queue.
|
java.lang.String |
toString()
Returns (a string string representing) the sequence of items
in the queue, in FIFO order, separated by spaces.
|
public boolean isEmpty()
public int size()
public Item peek()
java.util.NoSuchElementException
- if this queue is emptypublic void enqueue(Item item)
public Item dequeue()
java.util.NoSuchElementException
- if this queue is emptypublic java.lang.String toString()
toString
in class java.lang.Object
public java.util.Iterator<Item> iterator()
iterator
in interface java.lang.Iterable<Item>
public static void main(java.lang.String[] args)