ma'am audrey's lessons

ITC 120 › Prelim › Queues

Linear data structures · Lesson 4 of 4

Queues

This lesson teaches:Data structure

The oldest item leaves first, like a canteen line.

By the end, you can:

  1. explain the first-in, first-out (FIFO) rule and name places where it fits;
  2. trace enqueue, dequeue, and peek in a table, writing the queue from front to rear and the value each call returns;
  3. say what each LinkedQueue method changes in front, rear, and the links, including why rear is cleared when the queue becomes empty;
  4. trace a program that uses Java's own Queue<Integer> with offer, poll, and peek;
  5. choose a stack, queue, array, or linked list for a situation, and give a reason.

You need: the Linked lists and Stacks lessons.

Part 1 · The big idea

First come, first served

At the canteen, the student at the front of the line is served first and leaves. A new student joins at the back, called the rear. Nobody cuts in, and nobody leaves from the middle.

Canteen1234newfrontrearserved first, leavesthe front = dequeuejoins at the rear= enqueue
Students join at the rear and leave from the front, in the order they came.

Queue

A queue is a linear data structure (its items form one line) where items join at one end, the rear, and leave from the other end, the front. It follows the FIFO rule: first in, first out. The item that has waited longest is the first one removed.

Here is the definition as a picture. Four items joined, one after another:

A, B, C, D were enqueued in that orderABCDfrontrearleavesjoinsdequeueenqueuein:out:1st1st2nd2nd3rd3rd4th4thclosed sides: nobody cuts in or leaves from the middleFirst in (A) is the first out.
The items form one line, from the front (left) to the rear (right). Both ends are open, but each end has one job: items join only at the rear and leave only from the front. Read the two rows: A joined first and leaves first; D joined last and leaves last. That is FIFO.

What makes something a queue is the rule "join at the rear, leave from the front," not what holds the items. (In Part 4, a queue keeps its items in a linked list.)

Why follow such a strict rule? It is fair: whoever has waited longest goes next, and nobody can cut in or be skipped. Many tasks need exactly that, like serving people or printing jobs in the order they arrived.

Compare it with a stack: a stack uses one end and gives back the newest item; a queue uses two ends and gives back the oldest.

Here are the words that come with a queue:

WordMeaningIn the canteen line
frontthe item that leaves nextthe student being served
rearthe item that joined most recentlythe last student in line
enqueue(x)add x at the reara new student lines up
dequeue()remove the front item and return itthe front student is served and leaves
peek()return the front item, but keep it theresee who is next, without serving them
size()how many items the queue holdscount the students in line
isEmpty()true when there are no itemsnobody is in line

As with push and pop, these are ordinary method names a programmer writes, not Java keywords.

Underflow (and why there is no overflow here)

Underflow: dequeuing or peeking when the queue is empty. The queue in this lesson is built from a linked list, which has no fixed size, so it does not overflow: a new node can always be added (unless the computer runs out of memory). A queue stored in a fixed-size array can overflow.

Underflow: the queue is emptyCanteennobody in linedequeue()Nobodyto serve!In code: dequeue() or peek() when front == nullNo overflow: the line can always growCanteen+1A linked queue makes a new node for each item,so there is always room (until memory runs out).
Underflow is a mistake in when the program calls a method, not a problem with the data. In Part 4, dequeue and peek check for it first.

Where you see FIFO

Here are three everyday places where the item that waited longest goes first:

A shared printerJobs print in the order they were sent.printing job 1job 2job 3job 4just sentNow servingNumbers are called in the order they were taken.NOW SERVING015016017018just tookcalled nextLike a line, but you can sit while you wait.A music app's "Up next" listSongs you add to the queue go to the end.▶ Playing: Song 12. Song 23. Song 34. Song 4Add to queueplays first:it was addedfirst
In each one, the orange item has waited longest, so it goes first. The teal one just joined, so it goes last.

Queues fit any waiting line served in arrival order. Two more, one of which you will meet in a later lesson:

  • passengers at a pedicab terminal;
  • breadth-first search, which you will meet in the BFS lesson: it keeps the places it still has to visit in a queue.

These illustrate the rule; they do not describe how any particular system is programmed.

Part 2 · Try it

Queue lab

Enqueue three values, then dequeue them. In which order do they come out? Compare with the stack lab from the last lesson.

Queue lab

Type a value, then enqueue, dequeue, or peek. Every action is written in the log, like a trace table. Try dequeuing an empty queue.

Queue (FIFO)

OperationQueue (front → rear)Returned

Part 3 · Tracing

Tracing a queue in a table

The table works like the stack's, but the queue is written front → rear: the item that leaves next is on the left. The queue starts empty, and each row acts on the result of the row before it:

CallQueue after (front → rear)ReturnedsizeWhat happens
enqueue(10)10—110 joins; it is both front and rear.
enqueue(20)10, 20—220 joins at the rear; 10 is still the front.
enqueue(30)10, 20, 30—330 joins at the rear.
dequeue()20, 3010210 leaves; 20 is the new front.
peek()20, 30202Reads the front. Nothing changes.
enqueue(40)20, 30, 40—340 joins at the rear.

A dash (—) in the Returned column means the call gives nothing back: enqueue is a void method.

Exam traps

  1. Write the queue front → rear. The newest item goes on the right, and dequeue removes from the left, like A in . (A stack removes from the right.)
  2. A call removes even when nothing prints it. q.dequeue(); on its own line still removes the front item; write its value in the Returned column.

Part 4 · Java

A queue in Java, using a linked list

Node (from the Linked lists lesson)

A node is one box in a linked list. It holds a value, data, and a reference, next, to the node after it. next is null when no node comes after. A new node made with new Node(value) starts with next = null.

A linked list can insert and delete anywhere. A queue narrows that down to two places: front refers to the node that leaves next, and rear refers to the last node, where new nodes attach. Having rear means enqueue never has to walk the whole list to find the end.

Why keep rear, and why do items join at the rear and leave at the front, not the other way around? The picture shows both reasons:

Without rear: walk to find the endOnly front is kept. Where does a new node go?front783nullwalk 1walk 2found theend at lastWith rear: jump straight to the endrear.next = newNode; one step, any lengthfrontrearnewNode7835nullWhy not leave from the rear?Arrows point forward only. There is no way back.frontrear783null✗ no arrow back to 8To remove 3, node 8 must get next = null, butfinding 8 means walking from the front again.
Top: with only front, every enqueue would walk the whole list first. Middle: rear lets enqueue link the new node in one step. Bottom: removing at the rear would need the node before it, and a singly linked list has no arrows going back. Removing at the front takes one step (front = front.next;), so items leave there.
 1class LinkedQueue {
 2  Node front;    // first node (leaves next); null means empty
 3  Node rear;     // last node (joined last); null means empty
 4  int count;     // number of items
 5
 6  boolean isEmpty() {
 7    return front == null;
 8  }
 9  int size() {
10    return count;
11  }
12  // ... enqueue, dequeue, and peek below
13}

LinkedQueue is a class, just like ArrayStack in the Stacks lesson. LinkedQueue q = new LinkedQueue(); makes one queue object, and q.enqueue(7) runs that object's enqueue method ( ).

The fields have no starting values in the code, so Java gives them default values: null for references and 0 for int. A new queue (new LinkedQueue()) starts with front == null, rear == null, and count == 0. isEmpty() is a boolean method: it returns true exactly when front is null.

Now enqueue and dequeue. Follow them from an empty queue: enqueue 7, enqueue 8, then dequeue twice.

Walkthrough: enqueue(7), enqueue(8), dequeue(), dequeue()

Use Next to go step by step, or tap a line to jump to it.

newNode7nullfront = nullrear = null

count = 0

The queue starts empty: front and rear are null. enqueue(7) first makes a new node holding 7. newNode refers to it; its next is null.

Step 1 of 15
 1void enqueue(int value) { 2  Node newNode = new Node(value); 3  if (isEmpty()) { 4    front = newNode;       // the only node is both 5    rear = newNode;        // the front and the rear 6  } else { 7    rear.next = newNode;   // 1. old rear refers to new node 8    rear = newNode;        // 2. rear refers to the new node 9  }10  count++;11}1213int dequeue() {14  if (isEmpty()) {15    throw new IllegalStateException("Queue underflow: empty.");16  }17  int value = front.data;  // 1. save the front value18  front = front.next;      // 2. front moves to the next node19  if (front == null) {     // 3. the queue became empty,20    rear = null;           //    so rear must be cleared too21  }22  count--;23  return value;24}

peek only reads the front value. Like the other methods, it throws an IllegalStateException (Java's exception for "you asked at the wrong time") when the queue is empty:

 1int peek() {
 2  if (isEmpty()) {
 3    throw new IllegalStateException("Queue underflow: empty.");
 4  }
 5  return front.data;   // look only; front does not move
 6}

Each method is a linked-list operation you already know:

MethodLinked-list operationWhat changes
enqueueinsert at the endthe old rear's next, then rear
dequeuedelete the first nodefront (and rear too, when the last node leaves)
peekread the first nodenothing

The whole program

Here is everything in one runnable file. main does the walkthrough's calls, then a few more:

 1public class Main {
 2  public static void main(String[] args) {
 3    LinkedQueue q = new LinkedQueue();
 4    q.enqueue(7);
 5    q.enqueue(8);
 6    System.out.println(q.dequeue());  // 7
 7    System.out.println(q.dequeue());  // 8
 8    System.out.println(q.isEmpty());  // true
 9    q.enqueue(5);
10    System.out.println(q.peek());     // 5
11    System.out.println(q.size());     // 1
12  }
13}
14
15class Node {
16  int data;
17  Node next;
18  Node(int value) {
19    data = value;
20    next = null;
21  }
22}
23
24class LinkedQueue {
25  Node front;    // first node (leaves next); null means empty
26  Node rear;     // last node (joined last); null means empty
27  int count;     // number of items
28
29  boolean isEmpty() {
30    return front == null;
31  }
32  int size() {
33    return count;
34  }
35  void enqueue(int value) {
36    Node newNode = new Node(value);
37    if (isEmpty()) {
38      front = newNode;
39      rear = newNode;
40    } else {
41      rear.next = newNode;
42      rear = newNode;
43    }
44    count++;
45  }
46  int dequeue() {
47    if (isEmpty()) {
48      throw new IllegalStateException("Queue underflow: empty.");
49    }
50    int value = front.data;
51    front = front.next;
52    if (front == null) {
53      rear = null;
54    }
55    count--;
56    return value;
57  }
58  int peek() {
59    if (isEmpty()) {
60      throw new IllegalStateException("Queue underflow: empty.");
61    }
62    return front.data;
63  }
64}

▶ This program runs as is. Try it in the Programiz online compiler: tap Copy, paste it there, and press Run.

Java's own queue: Queue<Integer>

Java has no LinkedQueue; it is our own class, named for "a queue kept in a linked list." Java's own Queue is an interface: a list of methods that a class promises to have (the Sets lesson explains interfaces with a picture). You cannot make an object from an interface (new Queue<>() is a compile error), so you make an object of a class that has those methods, such as LinkedList, and keep the variable's type as Queue:

 1import java.util.LinkedList;
 2import java.util.Queue;
 3
 4public class Main {
 5  public static void main(String[] args) {
 6    Queue<Integer> q = new LinkedList<>();
 7    q.offer(7);
 8    q.offer(8);
 9    q.offer(9);
10    System.out.println(q.peek());
11    System.out.println(q.poll());
12    System.out.println(q.size());
13    System.out.println(q);
14    q.poll();
15    System.out.println(q.poll());
16    System.out.println(q.isEmpty());
17    System.out.println(q.poll());
18  }
19}

▶ This program runs as is. Try it in the Programiz online compiler: tap Copy, paste it there, and press Run.

The <Integer> works just like . Java's method names differ from ours, so here is how to read the new lines aloud:

CodeRead it asOur LinkedQueue
Queue<Integer> q"q is a queue of Integers"LinkedQueue q
= new LinkedList<>()"make a new, empty LinkedList to be the queue"new LinkedQueue()
q.offer(7)"add 7 at the rear"enqueue(7)
q.poll()"remove and return the front"dequeue()
q.peek()"look at the front"peek()
System.out.println(q)"print the whole queue," front → rear, like [8, 9](we did not write one)

On an empty queue, poll and peek return null

Our dequeue() throws an exception on an empty queue. Java's poll() and peek() return null instead, and the program goes on. Careful: int x = q.poll(); on an empty queue crashes with a NullPointerException, because null cannot become an int. So check first, the way the BFS lesson does: while (!q.isEmpty()). (Queue also has add, remove, and element, which throw an exception instead of returning null.)

Now trace the program, the same way as Part 3. Try it on paper first, then check:

Show the trace and the output

One row per line that calls the queue. "Printed" is what println shows; a call can return a value that nothing prints.

LineCallQueue after (front → rear)ReturnedPrinted
7offer(7)7—
8offer(8)7, 8—
9offer(9)7, 8, 9—
10peek()7, 8, 977
11poll()8, 977
12size()8, 922
13print the queue8, 9—[8, 9]
14poll()98(not printed)
15poll()(empty)99
16isEmpty()(empty)truetrue
17poll()(empty)nullnull

Output (checked in Java):

7
7
2
[8, 9]
9
true
null

You can also write Queue<Integer> q = new ArrayDeque<>(); (with import java.util.ArrayDeque;). The program prints the same output, and Java's documentation says ArrayDeque is usually faster than LinkedList as a queue. In this course you still write your own, so you can see what happens inside.

A queue in an array

A queue can also be kept in an array. If the front always stayed at index 0, every dequeue would have to shift all the other values one cell left, like deleting at index 0 in the Arrays lesson. So array queues let the front move forward instead, and when the rear reaches the last cell, it wraps around to index 0 to reuse the cells that were freed. This is called a circular array.

Enqueue 1 to 5, dequeue twice, enqueue 660free1324354frontrearafter cell 4 comes (4 + 1) % 5 = 0Queue, front → rear: 3, 4, 5, 6Cells 0 and 1 were freed by the two dequeues.The next enqueue goes in cell (0 + 1) % 5 = 1.
Five cells. The two dequeues moved front to cell 2. Then 6 had no cell to the right of cell 4, so rear wrapped around to cell 0. Read the queue from front, going right and wrapping: 3, 4, 5, 6.

The wrap-around uses the % (remainder) operator: the cell after index i is (i + 1) % data.length. With 5 cells, after index 4 comes (4 + 1) % 5 = 0. Unlike the linked queue, an array queue can overflow.

Part 5 · Watch out

Common mistakes

Mistake 1: forgetting rear = null

Situation: a student deletes the if (front == null) block (lines 19–21 of the walkthrough code), then runs the walkthrough again: enqueue 7, enqueue 8, and dequeue twice.

✓ With the if blockif (front == null) rear = null;front = nullrear = null(no nodes)Both say: empty.✗ Without the if blockfront moved on; rear was never clearedfront = nullrear8nullleft thequeuefront says empty; rear still says 8. They disagree.✗ What it could breakif isEmpty() checked rear == nullfront = null8rear5nullold 8enqueue(5) links 5 after the old node 8.front is still null, so 5 can never be dequeued.
Middle: the red box from step 13 of the walkthrough, but this time nothing clears rear. Bottom: one thing a leftover rear could break.

What goes wrong: front says the queue is empty, but rear still refers to node 8, which has left. Our enqueue still works, because isEmpty() checks front. But any code that trusts rear goes wrong, like the bottom panel.

Fix: when the last node leaves, clear both: if (front == null) rear = null;.

Mistake 2: moving rear before linking

Situation: a student swaps the two lines in the else part of enqueue:

} else {
  rear = newNode;        // moves first...
  rear.next = newNode;   // ...then links
}

What goes wrong: after rear = newNode;, rear already refers to the new node, so rear.next = newNode; makes the new node point to itself. The old last node still has next = null, so the new node was never linked in. With 7 in the queue, enqueue(8) then dequeue() returns 7, and the queue looks empty: 8 is lost.

✓ Link, then moverear.next = newNode; then rear = newNode;frontrear78nullqueue: 7, 8✗ Move, then link (swapped)rear = newNode; then rear.next = newNode;frontrear7null88 pointsto itselfnever linkeddequeue() returns 7, then front = 7.next = null.The queue looks empty: 8 is lost.
Top: the right order links 7 to 8. Bottom: swapped, 8 points to itself, and 7 still points to null.

Fix: link first (rear.next = newNode;), then move (rear = newNode;). Same idea as the in the Linked lists lesson.

Part 6 · Bringing it together

Stacks, queues, arrays, and linked lists

Same inputs, opposite orders

Add 1, 2, 3, then remove all three: a stack gives 3, 2, 1; a queue gives 1, 2, 3.

Stack: push 1, 2, 3123toppop 3 times:321newest first(LIFO)Queue: enqueue 1, 2, 3123frontreardequeue 3 times:123oldest first (FIFO)
The same three items in the same order. The stack hands back the newest first; the queue hands back the oldest first.

Try a longer sequence below: tap Same inputs, both structures.

Stack and queue lab

Type a value, then add or remove. Every action is written in the log, like a trace table. Then tap Same inputs, both structures.

Stack (LIFO · capacity 5)

Queue (FIFO)

OperationStack (bottom → top)Queue (front → rear)Returned
StackQueue
RuleLIFO: last in, first outFIFO: first in, first out
Add / removepush and pop at the top (same end)enqueue at the rear, dequeue at the front
Look onlypeek at the toppeek at the front
Written in a tracebottom → topfront → rear
Fits tasks likeundo, going back, reversingserving in arrival order

Arrays vs. linked lists

Here is how the two storage choices compare on common tasks:

TaskArraySingly linked list
Reach the value at index kone step, by indexfollow k links from head
Insert or delete near the frontshift the later valueschange one or two links
Insert after a node you already haveshift the later valueschange two links
Delete the last valuejust reduce the sizewalk to the node before it
Memory per itemthe value (plus unused cells)the value plus a reference

Rule vs. storage

LIFO and FIFO describe behavior: which item leaves next. An array or a linked list is storage: where the items are kept. Any rule can use either storage. These lessons showed an array stack and a linked queue, but a linked stack and an array queue work too (see the boxes "A stack built from a linked list" and "A queue in an array").

Part 7 · Your turn

Practice

Set A is the Section 6 self-check from your module, in case you want to redo it. Set B is new. The readiness check covers all prelim topics. The coding task at the end runs in Java.

Set A: from the module

  1. Write exactly what this prints.
    LinkedQueue q = new LinkedQueue();
    q.enqueue(3);
    q.enqueue(5);
    q.enqueue(8);
    System.out.println(q.dequeue());
    System.out.println(q.peek());
    q.enqueue(1);
    System.out.println(q.size());
  2. A LinkedQueue holds one node. After dequeue(), what are front and rear, and why must both change?
Show the answers
  1. 3, 5, 3. dequeue() removes 3; peek() shows 5; after enqueue(1) the queue is 5, 8, 1, so size() is 3.
  2. Both become null. The queue is empty, so there is no front or rear. If rear still referred to the removed node, front and rear would disagree.

Set B: new problems

  1. The statements run in order, starting with an empty queue. Copy the table and fill it in. The first row is done for you.
    LinkedQueue q = new LinkedQueue();
    q.enqueue(6);
    q.enqueue(14);
    q.dequeue();
    q.enqueue(9);
    q.enqueue(2);
    q.peek();
    q.dequeue();
    q.dequeue();
    StatementQueue after (front → rear)Value returned
    q.enqueue(6);6—
    q.enqueue(14);
    q.dequeue();
    q.enqueue(9);
    q.enqueue(2);
    q.peek();
    q.dequeue();
    q.dequeue();
  2. A LinkedQueue holds 4, 10, 15 (front to rear). (a) After enqueue(20), which node does rear refer to, and which node's next changed? (b) Then dequeue() runs three times. Which node do front and rear refer to now?
  3. Choose a stack or a queue, and give a reason: (a) a printer that prints jobs in the order they were sent; (b) a text box that removes the most recently typed letter when you press Backspace.
Show the answers

For self-study, not for grading. All answers were checked by running the code in Java.

  1. StatementQueue after (front → rear)Value returned
    q.enqueue(6);6—
    q.enqueue(14);6, 14—
    q.dequeue();146
    q.enqueue(9);14, 9—
    q.enqueue(2);14, 9, 2—
    q.peek();14, 9, 214
    q.dequeue();9, 214
    q.dequeue();29
  2. (a) rear refers to node 20, and node 15's next changed from null to node 20. (b) Both refer to node 20, the only node left: one node is both the front and the rear.
  3. (a) Queue: first sent, first printed. (b) Stack: the newest letter is removed first.

Readiness check (all prelim topics, from the module)

  1. The list is head → 4 → 9 → 2 → 7 → null. What does this print?
    Node current = head;
    int count = 0;
    while (current != null) {
      if (current.data > 3) {
        count++;
      }
      current = current.next;
    }
    System.out.println(count);
  2. Starting empty: add 1, add 2, remove, add 3, add 4, remove, remove. Which values are removed, in order, (a) if it is a stack, (b) if it is a queue? (Check it with the lab's "Same inputs" button above.)
  3. Choose a stack, queue, array, or linked list, and give a reason: (a) passengers riding in the order they arrived; (b) undoing the most recent drawing stroke first; (c) looking up the score in seat 25 many times a day, in a class that never changes size.
  4. True or false, with a reason: "Linked lists always insert and delete faster than arrays."
Show the answers
  1. 3. Three values (4, 9, and 7) are greater than 3.
  2. (a) Stack: 2, 4, 3 (1 is left). (b) Queue: 1, 2, 3 (4 is left).
  3. (a) Queue: first come, first served. (b) Stack: the most recent stroke is undone first. (c) Array: the size is fixed, and the seat number works as an index for direct access. Seat 25 is at index 24, since seats count from 1 but indexes count from 0.
  4. False. Changing links is quick, but reaching the right node can mean walking through the list. Deleting the last value is quicker in an array, and reading by position is direct only in an array.

Your coding task: a queue in an array

Part 4's box "A queue in an array" kept a queue in a circular array ( ). Here it is in Java, as our own class ArrayQueue. dequeue is done: it takes the value at front, then moves front to the next cell, wrapping around with %. Finish enqueue in about 6 lines where it says YOUR CODE. It does the same thing at the rear. Run it: the printed lines must match the comments.

 1public class Main {
 2  public static void main(String[] args) {
 3    ArrayQueue q = new ArrayQueue(4);
 4    q.enqueue(1);
 5    q.enqueue(2);
 6    q.enqueue(3);
 7    System.out.println(q.dequeue());  // expected: 1
 8    System.out.println(q.dequeue());  // expected: 2
 9    q.enqueue(4);
10    q.enqueue(5);                     // wraps around to cell 0
11    q.enqueue(6);                     // goes into cell 1
12    System.out.println(q.isFull());   // expected: true
13    while (!q.isEmpty()) {
14      System.out.print(q.dequeue() + " ");
15    }
16    System.out.println();             // expected: 3 4 5 6
17  }
18}
19
20class ArrayQueue {
21  int[] data;
22  int front;   // index of the front item
23  int rear;    // index of the rear item; -1 before the first enqueue
24  int count;   // number of items
25
26  ArrayQueue(int capacity) {
27    data = new int[capacity];
28    front = 0;
29    rear = -1;
30    count = 0;
31  }
32  boolean isEmpty() {
33    return count == 0;
34  }
35  boolean isFull() {
36    return count == data.length;
37  }
38  void enqueue(int value) {
39    // YOUR CODE:
40    // 1. If the queue is full, throw an IllegalStateException.
41    // 2. Move rear to the next cell, wrapping around with %.
42    // 3. Store the value there, and add 1 to count.
43
44  }
45  int dequeue() {
46    if (isEmpty()) {
47      throw new IllegalStateException("Queue underflow: empty.");
48    }
49    int value = data[front];
50    front = (front + 1) % data.length;   // move front, wrapping around
51    count--;
52    return value;
53  }
54}

▶ This program runs as is. Try it in the Programiz online compiler: tap Copy, paste it there, and press Run.

Before you write enqueue, the starter stops at the first dequeue with "Queue underflow: empty.", because nothing was added. That is expected.

Show one possible answer
 1void enqueue(int value) {
 2  if (isFull()) {
 3    throw new IllegalStateException("Queue overflow: full.");
 4  }
 5  rear = (rear + 1) % data.length;
 6  data[rear] = value;
 7  count++;
 8}

Output: 1, 2, true, then 3 4 5 6.

The table shows what happens inside the array (4 cells) as main runs. A dash means the cell was never used:

StatementCells 0, 1, 2, 3frontrearcount
new ArrayQueue(4)–, –, –, –0-10
enqueue 1, 2, 31, 2, 3, –023
dequeue() twice1, 2, 3, –221
enqueue(4)1, 2, 3, 4232
enqueue(5)5, 2, 3, 4203
enqueue(6)5, 6, 3, 4214

The two dequeues did not erase 1 and 2. They stay in their cells, but front moved past them, so they are no longer part of the queue. enqueue(5) found no cell after index 3, so rear wrapped around: (3 + 1) % 4 = 0, and 5 wrote over the old 1. Reading from front (cell 2) and wrapping gives 3, 4, 5, 6.

A common mistake is rear++; instead of the % line. Then enqueue(5) tries cell 4, and Java throws an ArrayIndexOutOfBoundsException, even though cells 0 and 1 are free.

Why does rear start at -1? The first enqueue moves it to (-1 + 1) % 4 = 0, so the first value goes into cell 0. It is the same idea as top = -1 in the Stacks lesson. And count makes isEmpty() and isFull() one comparison each. Without it, an empty queue and a full queue can have the same front and rear.

Part 8 · Check yourself

Self-check

Not graded. Tap an answer to see if you got it, and read why.

  1. A queue follows which rule?

  2. Enqueue 1, enqueue 2, enqueue 3, then dequeue. What is returned?

  3. In LinkedQueue, where does enqueue attach the new node?

  4. Why must rear.next = newNode; come before rear = newNode;?

  5. After the last node leaves, why does dequeue() also set rear = null?

  6. Students waiting at the registrar's window, served in the order they arrived. Which structure fits?

  7. Add 1, 2, 3 to a stack and to a queue, then remove one item from each. Which values come out?

  8. After Queue<Integer> q = new LinkedList<>(); q.offer(1); q.offer(2); q.offer(3); q.poll(); what does System.out.println(q.peek()); print?

  9. A Queue<Integer> is empty. What does q.poll() do?

Score: 0 / 9

Key takeaways

  1. Queue: first in, first out. Enqueue at the rear, dequeue at the front.
  2. dequeue removes and returns the front item; peek only looks.
  3. In LinkedQueue, enqueue links the old rear to the new node first, then moves rear.
  4. When the last node leaves, both front and rear become null.
  5. LIFO and FIFO are rules. Arrays and linked lists are storage. Any rule can use either.

You've finished the linear data structures and the prelim topics. Next: Trees and binary trees, the start of the midterm topics.

References

  1. R. Sedgewick and K. Wayne, Algorithms, 4th ed. Addison-Wesley, 2011, Section 1.3 (Bags, Queues, and Stacks). algs4.cs.princeton.edu
  2. P. Morin, "Linked Lists," Chapter 3 in Open Data Structures. opendatastructures.org
  3. Oracle, "Types, Values, and Variables" (default values), Chapter 4 in The Java Language Specification, Java SE 21. docs.oracle.com
  4. Oracle, "Class IllegalStateException," Java SE 21 API. docs.oracle.com
  5. ITC 120 Data Structures and Algorithms Syllabus, Faculty of Computing, Engineering, and Technology, Davao Oriental State University.