Queue/Usage

From Rosetta Code
Revision as of 22:55, 5 January 2009 by rosettacode>Kevin Reid (add Java example)
Task
Queue/Usage
You are encouraged to solve this task according to the task description, using any language you may know.

Data Structure
This illustrates a data structure, a means of storing data within a program.

You may see other such structures in the Data Structures category.

Illustration of FIFO behavior

Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.)

Operations:

  • push (aka enqueue) - add element
  • pop (aka dequeue) - pop first element
  • empty - return truth value when empty

Java

<java>

import java.util.LinkedList;
import java.util.Queue;
...
Queue<Integer> queue = new LinkedList<Integer>();
System.out.println(queue.peek() == null); // empty test - true
// queue.remove();       // would throw NoSuchElementException
queue.add(1);
queue.add(2);
queue.add(3);
System.out.println(queue);                // [1, 2, 3]
System.out.println(queue.remove());       // 1
System.out.println(queue);                // [2, 3]
System.out.println(queue.peek() == null); // false

</java>

Java 1.4 compatible version: <java>

import java.util.LinkedList;
...
LinkedList queue = new LinkedList();
System.out.println(queue.size() == 0);    // empty test - true
queue.add(new Integer(1));
queue.add(new Integer(2));
queue.add(new Integer(3));
System.out.println(queue);                // [1, 2, 3]
System.out.println(queue.removeFirst());  // 1
System.out.println(queue);                // [2, 3]
System.out.println(queue.size() == 0);    // false

</java>

Works with: UCBLogo

UCB Logo comes with a protocol for treating lists as queues.

make "fifo []
print empty? :fifo    ; true
queue "fifo 1
queue "fifo 2
queue "fifo 3
show :fifo            ; [1 2 3]
print dequeue "fifo   ; 1
show :fifo            ; [2 3]
print empty? :fifo    ; false