CS111 Lab 11

Queues



A queue is a container that implements the First-in-First-Out (FIFO) protocol.
The queue is defined as a interface. The LinkedList class implements the Queue interface

The following are essential methods of this interface:
  1. int size()
  2. add()
  3. isEmpty()
  4. poll()
  5. peek()


Part I

  1. What output is produced by the following segment of code?
      Queue<Integer> q= new LinkedList<Integer>()
      System.out.println("TASK 1:");
      for (int i = 1; i <= 5; i++)
        q.add(i);
      System.out.println(q.toString());

      System.out.println("\nTASK 2:");
      System.out.println(q.peek());
      System.out.println(q.toString());

      System.out.println("\nTASK 3:");
      q.add(77);
      q.add(88);
      q.remove();
      System.out.println(q.toString());

      System.out.println("\nTASK 4:");
      while (!q.isEmpty())
        System.out.println(q.poll() + " is at the front");




  2. An Object template can be used to accept generic data types. In the code below, Object is used to describe a generic queue. What output is displayed ?

      Queue<Object> names = new LinkedList<Object>();
      names.add("Bobo");
      names.add("Billy");
      names.add("Suzy");
      names.remove();
      names.add("Ari");
      names.remove();

      System.out.println(names.toString());


    Part III: Simulation using a Queue


      The childhood game of Hide and Seek involves determining who is to be "It".
      1. Players stand in a line while one of the players recites a rhyme, such as "You are out"
        to count off players, eliminating every 3rd player - 3 because the rhyme contains three syllables.
      2. The process stops when only one player remains.

      This process can be simulated using a queue.
      The diagram below shows seven players in the elimination process as simulated by a queue.
      Queue Action: Count off two people in line.
      Bobo Ruth Ned Sam Ari Barb Lucy Count off Bobo and Ruth - Add to the back of the line
      Ned Sam Ari Barb Lucy Bobo Ruth Elinimate Ned
      Sam Ari Barb Lucy Bobo Ruth Count off Sam and Ari
      Barb Lucy Bobo Ruth Sam Ari Elinimate Barb
      Lucy Bobo Ruth Sam Ari Count off Lucy and Bobo - Add to the back of the line
      Ruth Sam Ari Lucy Bobo Elinimate Ruth
      Sam Ari Lucy Bobo Count off Sam and Ari - Add to the back of the line
      Lucy Bobo Sam Ari Elinimate Lucy
      Bobo Sam Ari Count off Bobo and Sam - Add to the back of the line
      Ari Bobo Sam Elinimate Ari
      Bobo Sam Count off Bobo and Sam - Add to the back of the line
      Bobo Sam Elinimate Bobo
      Sam Sam is the only person left in line therefore she is IT.