Ueues and Inked Ists: - Queues - Linked Lists - Double-Ended Queues
Ueues and Inked Ists: - Queues - Linked Lists - Double-Ended Queues
head
tail
Queues
A queue differs from a stack in that its insertion and removal routines follows the rst-in-rst-out (FIFO) principle. Elements may be inserted at any time, but only the element which has been in the queue the longest may be removed. Elements are inserted at the rear (enqueued) and removed from the front (dequeued)
front a0 a1 a2
rear
...
an-1
- dequeue(): Remove the object from the front of the queue and return it; an error occurs if the queue is empty These support methods should also be dened: - size(): Return the number of objects in the queue
- isEmpty(): Return a boolean value that indicates whether the queue is empty
- front():
Return, but do not remove, the front object in the queue; an error occurs if the queue is empty
An Array-Based Queue
Create a queue using an array in a circular fashion A maximum size N is specied, e.g. N = 1,000. The queue consists of an N-element array Q and two integer variables: - f, index of the front element - r, index of the element after the rear one normal conguration
Q 0 1 2
... f r
N1
N1
What does f=r mean? How do we compute the number of elements in the queue from f and r?
the head of the list is the front of the queue, the tail of the list is the rear of the queue why not the opposite?
Double-Ended Queues
A double-ended queue, or deque, supports insertion and deletion from the front and back. The Deque Abstract Data Type - insertFirst(e): Insert e at the deginning of deque. - insertLast(e): Insert e at end of deque - removeFirst(): Removes and returns rst element - removeLast(): Removes and returns last element Additionally supported methods include: - rst() - last() - size() - isEmpty()
10
11
Baltimore
New York
Providence
A node of a doubly linked list has a next and a prev link. It supports the following methods: - setElement(Object e) - setNext(Object newNext) - setPrev(Object newPrev) - getElement() - getNext() - getPrev() By using a doubly linked list, all the methods of a deque run in O(1) time.
Queues and Linked Lists 12
Baltimore
New York
Providence
13
Baltimore
New York
Providence
San Francisco
Baltimore
New York
Providence
San Francisco
header
trailer
Baltimore
New York
Providence
14