CS2006 - Data Structures I
Chapter 8
Queue I
2
Topics
Introduction Queue Application Implementation
Linked List
3
Queues A queue differs from a stack in that it follows the
first-in-first-out (FIFO) principle. Inserting an item to the rear is known as
"enqueueing". Removing an item from the front is known as
"dequeueing".
cashier
Front of line Back of line
4
Queues Linear, homogeneous structure Has First-In-First-Out (FIFO) behavior;
Items added at one end and removed from the other end
Middle elements are logically inaccessible
Add/
Enqueue
Remove/Dequeue
Back/Rear Front/Head
5
Queue Applications
Real-World Applications Buy a movie ticket Cashier lines in any store
Computer Science Applications Print lines of a document Convert digit strings to decimal
6
ADT Queue
Specification: Elements
Homogeneous Linear
Operations Create an empty queue Check if a queue is empty / Full Enqueue (Enq, Enque, Add, Insert):
Adding new element at the back (rear) Dequeue (Deq, Deque, Remove, Serve):
Deleting an element from the front Retrieve an element from a queue
7
Queue Applications Converting Digit Strings to Decimal
Enter characters from the keyboard and retain them in order
Assumption: No typing mistakes Blank spaces may precede or follow the digits
Formula used: Initial value
DigitSum = 0
8
Queue Applications Converting Digit Strings to Decimal
Pseudocode// Convert digits in aQueue into decimal integer n// Get first digit, ignoring any leading blanksdo {
ch=queue.dequeue()} while ( ch is blank)// Assertion: ch contains first digit// Compute n from digits in queuen = 0;done = false;do { n = 10 * n + integer that ch represents
if (! queue.isEmpty( ) ) ch=queue.dequeue()
elsedone = true
} while (! done and ch is a digit)// Assertion: n is result
9
Queue Applications
Recognizing Palindromes Uses a queue & a stack Idea:
1. Insert the string in both queue & stack2. Remove characters from both stack's Top & queue's Front,
comparing them3. Repeat until:
a) Either the stack or the queue are empty String is a palindrome
b) The character from the stack and the corresponding character from the queue are not similar String isn't a palindrome
10
Queue Applications Recognizing Palindromes
PseudocodeIsPal(in str:string) : boolean// Determines whether String is a palindromeaQueue.createQueue ( ) // Create an empty queue aStack.createStack ( ) // Create an empty stack// Insert each character of String into both aQueue and aStacklength = length of strfor ( i = 1 through length){ nextChar = ith character of str
aQueue.enqueue ( nextChar )aStack.push(NextChar)
} // end for// Compare aQueue with aStackcharactersAreEqual = true;while ( ! aQueue.isEmpty() && charactersAreEqual){ queueFront =aQueue.peek ()
stackTop= aStack.top ()if ( queueFront equals stackTop){ aQueue.dequeue ( )
aStack.pop ( )} else charactersAreEqual = false
} // end whilereturn charactersAreEqual
11
ADT Queue Implementation
Possible implementations:
Linked List-based Linear Circular
Array-based Linear Circular
ADT List-based
12
Linked List-Based Implementation More straightforward than array-based Possible options:
Linear linked list Two external “pointer” (Front & Back)
Circular linked list One “pointer” will be enough (Back)
13
Linked List Queue Implementation
Linked List -Based Implementation: Option 1 Insertion to an empty list
front = newNodeback = newNode
14
Linked List Queue Implementation
LL -Based Implementation: Option 1 Insertion to a non-empty list
newNode.setNext ( NULL);Back.setNext (newNode);back = newNode;
Deletiontemp = front ;front = front.getNext()temp.setNext ( NULL )
20 15
front
26 84
back
15
Linked List Queue Implementation
LL -Based Implementation: option 1 Deletion
form a one-node (one item) queueIf (front = back&&front!=null){
back = null front=null }
We will use option 2 to implement our queue
16
Queue Interface
public interface QueueInterface {
public boolean isEmpty(); public void enqueue(Object newItem) throws
QueueException; public Object dequeue() throws QueueException; public void dequeueAll(); public Object peek() throws QueueException;}
17
Queue Exception
public class QueueException extends RuntimeException {
public QueueException(String s) {
super(s);
} // end constructor
} // end QueueException
18
LListQueue Implementationpublic class LListQueue implements QueueInterface {
private Node lastNode; // we use option 2
public LListQueue() { lastNode = null; } // end default constructor
// queue operations: public boolean isEmpty() { return lastNode == null; } // end isEmpty
public boolean isFull() { return false; } // end isFull
public void dequeueAll() { lastNode = null; } // end dequeueAll
19
LListQueue Implementationpublic class LListQueue implements QueueInterface {
private Node lastNode;
public LListQueue() { lastNode = null; } // end default constructor
// queue operations: public boolean isEmpty() { return lastNode == null; } // end isEmpty
public boolean isFull() { return false; } // end isFull
public void dequeueAll() { lastNode = null; } // end dequeueAll
20
LListQueue Implementation (2) public void enqueue(Object newItem) { Node newNode = new Node(newItem); if(isFull()) throw new QueueException("QueueException on enqueue:"+ "queue full"); // insert the new node if (isEmpty()) { // insertion into empty queue newNode.setNext(newNode); } else { // insertion into nonempty queue newNode.setNext(lastNode.getNext()); lastNode.setNext(newNode); } // end if lastNode = newNode; // new node is at back } // end enqueue
21
LListQueue Implementation (3) public Object dequeue() throws QueueException { if (!isEmpty()) { // queue is not empty; remove front Node firstNode = lastNode.getNext(); if (firstNode == lastNode) { // special case? lastNode = null; // yes, one node in queue } else { lastNode.setNext(firstNode.getNext()); } // end if return firstNode.getItem(); } else { throw new QueueException("QueueException on dequeue:" + "queue empty"); } // end if } // end dequeue
22
LListQueue Implementation (4) public Object peek() throws QueueException { if (!isEmpty()) { // queue is not empty; retrieve front Node firstNode = lastNode.getNext(); return firstNode.getItem(); } else { throw new QueueException("QueueException on peek:" + "queue empty"); } // end if } // end peek } // end ListQueue
23
LListQueue Implementation (4) public Object peek() throws QueueException { if (!isEmpty()) { // queue is not empty; retrieve front Node firstNode = lastNode.getNext(); return firstNode.getItem(); } else { throw new QueueException("QueueException on peek:" + "queue empty"); } // end if } // end peek } // end ListQueue
24
LListQueue Testpublic class LListQueueTest {
public static void main(String[ ] args) { LListQueue aQueue = new LListQueue(); System.out.println("Enqueuing:"); for (int i = 0; i < 9; i++) { System.out.print(" "+i); aQueue.enqueue(new Integer(i)); } // end for System.out.println("\nDequeuing:"); for (int i = 0; i < 9; i++) { System.out.print(" "+aQueue.dequeue()); } // end for System.out.println(); } // end main} // QueueTest
25
Review In a queue, items can be added ______.
only at the front of the queue only at the back of the queue either at the front or at the back of the queue at any position in the queue
26
Review Operations on a queue can be carried out
at ______. its front only its back only both its front and back any position in the queue
27
Review Which of the following is NOT an ADT
queue operation? enqueue isEmpty Pop peek
28
Review The ______ operation retrieves and
removes the front of a queue. isEmpty enqueue dequeue peek
29
Review The ______ operation retrieves the item
that was added earliest to a queue, but does not remove that item. enqueue dequeue dequeueAll peek
30
Review A reference-based implementation of a
queue that uses a linear linked list would need at least ______ external references. one two three four
31
Review A reference-based implementation of a
queue that uses a circular linked list would need at least ______ external references. one two three four
32
Review Which of the following operations leaves a
queue unchanged? enqueue dequeue dequeueAll peek