• No results found

lecture-8-ADTqueue-2011-1.pdf

N/A
N/A
Protected

Academic year: 2020

Share "lecture-8-ADTqueue-2011-1.pdf"

Copied!
44
0
0

Loading.... (view fulltext now)

Full text

(1)

Queue ADT

Queue ADT

• Def : A queue is a list of items from which items

q

may be deleted at one end called “front” and

which items may be added at the other end

called “rear”

called rear .

• Queue organizes entries according to order of

entry

entry

• Queue types:

– Regular queueg q

(2)

Regular queue

Regular queue

• In this type of queue the first element

In this type of queue the first element

inserted is the first element to be removed.

So it is a FIFO structure

So it is a FIFO structure.

• Logical view

rear

N h i i

A B C

rear

Note: among the items in a queue, the one added first, or earliest, is the front of the queue, and the one added

front

queue, and the one added most recently is the back of the queue.

(3)
(4)

Queue ADT specification

Queue ADT specification

• Data

Data

– A collection of objects in a specific order

• OPERATIONS

OPERATIONS

Enqueue Task: Adds a new entry to the back of the queue. Input: newEntry is the new entry.

Output: None.

Dequeue() Task: Removes and returns the front of the queue.

I t N

Input: None.

(5)

Queue ADT specification

Queue ADT specification

getFront() Task: Retrieves the front of the queue without h i h i

changing the queue in any way. Input: None.

Output: Returns either the front of the queue or null if the queue is empty

the queue is empty.

isEmpty() Task: Determines whether the queue is empty. Input: None.

Output: Returns true if the queue is empty Output: Returns true if the queue is empty. • Clear() Task: Removes all entries from the queue.

Input: None. Output: None.p

Note: Alternate names for methods:

(6)

Queue Interface

Queue Interface

Public interface queueInterface{q {

/** Task: Adds a new entry to the back of the queue. *@param newentry an Object to be added*/

public Void enqueue(Object newEntry);

/** f f

/** Task: Removes and returns the front of the queue.

*@return either the Object at the front of the queue or null * if the queue was empty /if the queue was empty*/

(7)

Queue Interface

Queue Interface

/** Task: Retrieves the front of the queue

*@return either the Object at the front of the queue or null * if the queue was empty*/

public Object getFront(); public Object getFront();

/* Task: Determines whether the queue is empty. *@return true if the queue is empty */

*@return true if the queue is empty */

public Boolean isEmpty();

/** Task: Removes all entries from the queue.*/

public Void clear();

(8)

Example how to use Queue ADT

QueueInterface myQueue = new LQueue(); myQueue.enqueue(“Rami”);

myQueue enqueue(“Firas”); myQueue.enqueue( Firas ); myQueue.enqueue(“Ruslan”); myQueue.enqueue(“Hadi”);

Q (“S i”) myQueue.enqueue(“Sami”);

String front = (String) myQueue.getFront();

System.out.printIn(front + “ is at the front of the queue.”) F t (St i ) Q d ()

Front = (String) myQueue.dequeue();

System.out.printIn(front + “ is removed from the queue.”); myQueue.enqueue(“Amer”);

frnt = (String) myQueue.getFront();

System.out.printIn(front +” is at the front of the queue.”); Front = (String) miQueue.dequeue();

(9)

A Linked Implementation of a Queue

A Linked Implementation of a Queue

• Use chain of linked nodes for the queue

Use chain of linked nodes for the queue

– Two ends at opposite ends of chain

Accessing last node inefficient

– Accessing last node inefficient

– Could keep a reference to the tail of the chain

Pl

f

t f

t b

i

i

f h i

• Place front of queue at beginning of chain

• Place back of queue at end of chain

(10)
(11)
(12)

A Linked Implementation of a Queue

public class LQueue implements QueueInterface{ private Node frontNode; // references node for front of queue

private Node backNode; // references node for back of queue

private Node backNode; // references node for back of queue

public LQueue()

{

frontNode = null; backNode = null;

} // end default constructor

public Object getFront() { Object front = null;

{ j

if (!isEmpty())

front = frontNode. data; return front;

(13)

A Linked Implementation of a Queue

A Linked Implementation of a Queue

public void enqueue(Object newEntry)

p

q

(

j

y)

{ Node newNode = new Node(newEntry, null);

if (isEmpty())

(

p y())

frontNode = newNode;

else

backNode. next = newNode;

backNode = newNode;

(14)

A Linked Implementation of a Queue

A Linked Implementation of a Queue

public Object dequeue()

p j q ()

{ Object front = null; if (!isEmpty())

{ front = firontNode. data;

frontNode = frontNode.next ;

f (f )

if (frontNode == null) backNode = null; } // end if

(15)

A Linked Implementation of a Queue

A Linked Implementation of a Queue

public boolean isEmpty()

public boolean isEmpty()

{ return frontNode == null;

} // end isEmpty

} // end isEmpty

public void clear()

public void clear()

{ firontNode = null;

(16)

Circular Linked Implementations of a Queue

C cu a

ed

p e e tat o s o a Queue

• Last node references first node

Last node references first node

– Now we have a single reference to last node

And still locate first node quickly

– And still locate first node quickly

• No node contains a null

A circular linked chain with an

external reference to its last node that (a) has more than one node; (b) has one node; (c) is empty node; (c) is empty.

(17)

A Two-Part Linked Chain

A Two Part Linked Chain

• Linked nodes that form the queue followed by

Linked nodes that form the queue followed by

linked nodes available for use in the queue

queueNode references front of queue node

freeNode references first available node following

end of queue

• In essence we have two chains

– One for the queue

O f il bl d

(18)

A Two-Part Linked Chain

A Two Part Linked Chain

A two-part circular linked chain that represents both a queue and the nodes available to the queue.

(19)

A Two-Part Linked Chain

A Two Part Linked Chain

A two-part circular linked chain that represents a queue: (a)

when it is empty; (b) after adding one entry; (c) after adding three one entry; (c) after adding three more entries.

If freeNode.next== queueNode then we to add a new Node we then we to add a new Node, we have to leave one Node Unused -The Queue is empty if

queueNode==freeNode

-The Queue is full if

(20)

A Two-Part Linked Chain

A Two Part Linked Chain

A two-part circular linked chain that represents a queue: (d) after removing the front;

(e) after adding one (e) after adding one more entry

(21)

A Two-Part Linked Chain

A Two Part Linked Chain

(22)

A Two-Part Linked Chain

A Two Part Linked Chain

A chain with a node available for an addition to a queue: (a) before the addition; (b) after the addition

(23)

A Two-Part Linked Chain implementation

A Two Part Linked Chain implementation

public class TwoPartCircularLinkedQueue implements

p Q p

QueueInterface{

private Node queueNode; // references first node in queue private Node freeNode; // references node after back of queue public TwoPartCircularLinkedQueue()

{{

freeNode = new Node(null, null); freeNode next=freeNode;

(24)

A Two-Part Linked Chain implementation

A Two Part Linked Chain implementation

public void enqueue(Object newEntry) {

if (isChainFull()) {

// allocate a new node and insert it after node that freeNode references

Node newNode = new Node(null, freeNode.next); freeNode.next= newNode;

} // end if

freeNode.data= newEntry; freeNode = freeNode.next;; } // end enqueue

(25)

Array Based implementation of a Queue ADT

ay

ased

p e e tat o o a Queue

1. Fixed front: when the operation dequeue used,

p

q

then the all elements of the array must be

shifted. [inefficient]

2

Use two indexes: [frontIndex and backIndex]

2. Use two indexes: [frontIndex and backIndex] .

In this case the indexes moved instead of

moving elements. so when we dequeue the

queue we move the frontIndex and when we

queue we move the frontIndex and when we

enqueue the queue we move the backIndex.

This type of implementation has some

problems as follows:

problems as follows:

– the queue may become full by backIndex,

(26)

Problems with two indexes implementation of a queuep q

• Example: the array size of queue is 4 then

Example: the array size of queue is 4 then

enqueue(“A”); enqueue(“B”); enqueue(“C”); enqueue(“D”);

Not allowed the queue is full but it is not , one location is available, or double the array to allow this operation

A A

A B C D

dequeue(); enqueue(“E”);

(27)

Array Based implementation of a Queue ADT

3 Ci l th id i t t li i t

3. Circular array: the idea is to convert linear queue into circular queue such that the element queue[0],

immediately follows the element queue[queuesize-1].

O th h th d f th

• Once the queue reaches the end of the array, we can add entries to the beginning of the array.

• In order to implement the above idea we can use one of the following:

of the following:

– Using if statement

• If (backIndex == size-1) bakcindex=0; • If(frontIndex == size-1) frontIndex=0;If(frontIndex size 1) frontIndex 0;

– Using reminder operation

• frontIndex = (frontIndex + 1)%size • backIndex = (backIndex +1)%size

• In this type of implementation the best condition for indicating empty queue is to make the

(28)

Array Based implementation of a Queue ADT

ay

ased

p e e tat o o a Queue

4. Leaving one of array locations unused

4. Leaving one of array locations unused

(reserved location): which is follows the

backIndex of the queue

q

In this type of implementation the full

condetion will be:

(backIndex+1)% size==frontIndex

5. Use counter: if its value=0, then the

(29)

Array Based implementation of a Queue ADT

public class AQueue implements QueueInterface {

private Object[] queue; // circular array of queue entries private int frontIndex;

private int frontIndex; private int backIndex;

private static final int _MAX-SIZE = 50; public AQueue()

p () {

queue = new Object [MAX-SIZE]; frontIndex = MAX-SIZE-1;

backIndex = MAX-SIZE-1; } // end default constructor

public ArrayQueue(int initialMaxSize) {{

(30)

Array Based implementation of a Queue ADT

public void enqueue(Object newEntry) { if (isFull()) // isFull is private

{ ( ()) p

doubleArray();

backIndex = (backIndex + 1) % queue.length; queue[backIndex] = newEntry;

queue[backIndex] = newEntry; } // end enqueue

bli Obj t tF t()

public Object getFront() { Object front = null;

if (!isEmpty())( p y())

Int x=(frontIndex + 1) % queue.length; front = queue[x];

(31)

Array Based implementation of a Queue ADT

public Object dequeue()

{ Object front = null; if (!isEmpty())

{ frontIndex =(frontIndex + 1) % queue.length; front = queue[frontIndex];

queue[frontIndex] = null; } // end if

return front; } // end dequeue

public boolean isEmpty()

{ return frontIndex == backIndex ;

{ ;

} // end isEmpty

(32)

Array Based implementation of a Queue ADT

ay

ased

p e e tat o o a Queue

private void doubleArray()

{ Object[] oldQueue = queue; int oldSize = oldQueue.length; queue = new Object[2*oldSize]; queue new Object[2 oldSize]; int index

for (index = 0; index < oldSize - 1; index++) { frontIndex = (frontIndex + 1) % oldSize; { frontIndex = (frontIndex + 1) % oldSize;

queue[index] = oldQueue[frontIndex]; } // end for

frontIndex = queue.length-1; backIndex = index - 1;

(33)

Vector-Based Implementation of a Queue

ecto

ased

p e e tat o o a Queue

• Maintain front of queue at beginning of

Maintain front of queue at beginning of

vector

• Use

Use

addElement

addElement

method to add entry at

method to add entry at

back

– Vector expands as necessary

p

y

• When remove front element, remaining

elements move so new front is at

beginning of vector

(34)

Vector-Based Implementation of a Queue

Vector Based Implementation of a Queue

(35)

Vector-Based Implementation of a Queue

import java.util.Vector;

public class VQueue implements queueInterface { private Vector queue;// queue front is first in the vector

public VQueue()

{ queue = new Vector(); // t d bl i i if

{ queue = new Vector(); // vector doubles in size if ecessary

} // end default constructor

public VQueue(int maxSize) public VQueue(int maxSize) {

queue = new Vector(maxSize);

q ( )

(36)

Vector-Based Implementation of a Queue

Vector Based Implementation of a Queue

public void enqueue(Object newEntry)

p q ( j y)

{ queue.addElement(newEntry); } // end enqueue

public Object getFront()

{ O f

{ Object front = null; if (!isEmpty())

front = queue firstElement(); front = queue.firstElement(); return front;

(37)

Vector-Based Implementation of a Queue

bli Obj t d ()

public Object dequeue() { Object front = null;

if (!isEmpty())( p y())

{ front = queue.firstElement(); queue.removeElementAt(0); } // d if

} // end if return front; } // end dequeue } // end dequeue

public boolean isEmpty()

(38)

Specifications of the ADT Deque

Specifications of the ADT Deque

• A Double ended queue

A Double ended queue

• Has operations that

Add

t i

t i

– Add, remove, or retrieve entries

– At both its front and back

(39)
(40)

DeQue Interface

DeQue Interface

public interface DequeInterface {

p q {

public void addToFront(Object newEntry); public Void addToBack(Object newEntry); public Object removeFront();

public Object removeBack();

O ()

public Object getFront(); public Object getBack(); public Boolean isEmpty(); public Boolean isEmpty(); public Void clear();

(41)

Examp;e how to use DeQue ADT

Examp;e how to use DeQue ADT

DequeInterface myDeque = new LDeque();

q

y

q

q

();

myDeque.addToFront(“Firas”);

myDequeue.addToBack(“Ruslan”);

y

q

(

);

myDeque.addToFront(“Amer”);

myDeque.addToBack(“Sami”);

String name = myDeque.getFront();

myDeque.addToFront(name);

myDeque.removeFront();

(42)

Specifications of the ADT

P i it Q

Priority Queue

• Organizes objects according to priorities

Organizes objects according to priorities

– Contrast to regular queue in order of arrival

• Priority queue example – a hospital ER

Priority queue example a hospital ER

• Priority can be specified by an integer

– Must define whether high number is high

– Must define whether high number is high

priority or …

– Low number (say 0) is high priority

(

y )

g p

y

• Other objects can specify priority

(43)

Priority Queue Interface

Priority Queue Interface

public interface

PriorityQueueInterface

public interface

PriorityQueueInterface

{

public void

add(Comparable newEntry);

public

Comparable remove();

public

Comparable get();

public boolean

isEmpty();

bli i t

tSi

()

public int

getSize();

public void

clear();

(44)

References

Related documents

UNESCO World Heritage Site’s indicators of success and the tools used to measure this mainly focus on the maintenance of the site’s Outstanding Universal Value, its

Course restriction override permit: Some courses will be “closed” for registration or will have a “prerequisite” restriction other than class/college/major.. These restrictions

Trumm et al (2013) assessed the impact of the advanced technology of the new ExAblate 2100 system (Insightec Ltd, Haifa, Israel) for MRI-guided focused ultrasound surgery on

Chief Postel is an active member of the California Fire Chiefs Association (CFCA), the International Fire Code Institute, the International Association of Fire Fighters (IAFF) Local

The empirical evidence indicate that balance budget rules, their formal enforcement procedures, and expenditure rules contribute to the effectiveness of FD in achieving

In Feminist Judgments: From Theory to Practice, ed Rosemary Hunter, Clare McGlynn and Erika Rackley, 30-43. Oxford:

approach has been assessed over the course of history; it has also looked abnormal [3] Various factors, such as employment for women, the availability of contraceptives

It is said that a country’s currency peg can become currency manipulation representing protracted government intervention in the foreign exchange market that gives it unfair