stacks and queuescsc311: data structures1 chapter 5 stacks and queues objectives –stacks and...

30
Stacks and Queues Stacks and Queues CSC311: Data Structures CSC311: Data Structures 1 Chapter 5 Chapter 5 Stacks and Queues Stacks and Queues Objectives Objectives Stacks and implementations Stacks and implementations Queues and implementations Queues and implementations Double-ended queues and Double-ended queues and implementation implementation

Post on 21-Dec-2015

226 views

Category:

Documents


4 download

TRANSCRIPT

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 11

Chapter 5Chapter 5Stacks and QueuesStacks and Queues

ObjectivesObjectives

– Stacks and implementationsStacks and implementations– Queues and implementationsQueues and implementations– Double-ended queues and implementationDouble-ended queues and implementation

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 22

Abstract Data Types (ADTs)Abstract Data Types (ADTs)

An abstract data type (ADT) is an An abstract data type (ADT) is an abstraction of a data structureabstraction of a data structureAn ADT specifies:An ADT specifies:– Data storedData stored– Operations on the dataOperations on the data– Error conditions associated with Error conditions associated with

operationsoperations

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 33

ADT ExampleADT ExampleExample: ADT modeling a simple stock Example: ADT modeling a simple stock trading systemtrading system– The data stored are buy/sell ordersThe data stored are buy/sell orders– The operations supported areThe operations supported are

order buy(stock, shares, price)order buy(stock, shares, price)

order sell(stock, shares, price)order sell(stock, shares, price)

void cancel(order)void cancel(order)

– Error conditions:Error conditions:Buy/sell a nonexistent stockBuy/sell a nonexistent stock

Cancel a nonexistent orderCancel a nonexistent order

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 44

The Stack ADTThe Stack ADTThe The StackStack ADT stores ADT stores arbitrary objectsarbitrary objectsInsertions and deletions Insertions and deletions follow the last-in first-follow the last-in first-out schemeout schemeThink of a spring-Think of a spring-loaded plate dispenserloaded plate dispenserMain stack operations:Main stack operations:– pushpush(object): inserts an (object): inserts an

elementelement– object object poppop(): removes (): removes

and returns the last and returns the last inserted elementinserted element

Auxiliary stack Auxiliary stack operations:operations:– object object toptop(): returns (): returns

the last inserted the last inserted element without element without removing itremoving it

– integer integer sizesize(): returns (): returns the number of the number of elements storedelements stored

– boolean boolean isEmptyisEmpty(): (): indicates whether no indicates whether no elements are storedelements are stored

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 55

Stack Interface in JavaStack Interface in Java

Java interface Java interface corresponding to corresponding to our Stack ADTour Stack ADTRequires the Requires the definition of definition of class class EmptyStackExceptionEmptyStackExceptionDifferent from Different from the built-in Java the built-in Java class class java.util.Stackjava.util.Stack

public interface Stack {

public int size();

public boolean isEmpty();

public Object top()throws EmptyStackException;

public void push(Object o);

public Object pop() throws EmptyStackException;

}

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 66

ExceptionsExceptions

Attempting the Attempting the execution of an execution of an operation of ADT operation of ADT may sometimes may sometimes cause an error cause an error condition, called an condition, called an exceptionexception

Exceptions are said Exceptions are said to be “thrown” by to be “thrown” by an operation that an operation that cannot be executedcannot be executed

In the Stack ADT, In the Stack ADT, operations pop and operations pop and top cannot be top cannot be performed if the performed if the stack is emptystack is empty

Attempting the Attempting the execution of pop or execution of pop or top on an empty top on an empty stack throws an stack throws an EmptyStackExceptionEmptyStackException

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 77

Applications of StacksApplications of StacksDirect applicationsDirect applications– Page-visited history in a Web browserPage-visited history in a Web browser– Undo sequence in a text editorUndo sequence in a text editor– Chain of method calls in the Java Virtual Chain of method calls in the Java Virtual

MachineMachine

Indirect applicationsIndirect applications– Auxiliary data structure for algorithmsAuxiliary data structure for algorithms– Component of other data structuresComponent of other data structures

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 88

Method Stack in the JVMMethod Stack in the JVMThe Java Virtual Machine (JVM) The Java Virtual Machine (JVM) keeps track of the chain of keeps track of the chain of active methods with a stackactive methods with a stackWhen a method is called, the When a method is called, the JVM pushes on the stack a JVM pushes on the stack a frame containingframe containing– Local variables and return valueLocal variables and return value– Program counter, keeping track Program counter, keeping track

of the statement being executed of the statement being executed

When a method ends, its When a method ends, its frame is popped from the frame is popped from the stack and control is passed to stack and control is passed to the method on top of the the method on top of the stackstackAllows for Allows for recursionrecursion

main() {int i = 5;foo(i);}

foo(int j) {int k;k = j+1;bar(k);}

bar(int m) {…}

bar PC = 1 m = 6

foo PC = 3 j = 5 k = 6

main PC = 2 i = 5

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 99

Array-based StackArray-based Stack

A simple way of A simple way of implementing the implementing the Stack ADT uses an Stack ADT uses an arrayarrayWe add elements We add elements from left to rightfrom left to rightA variable keeps A variable keeps track of the index track of the index of the top element of the top element

S0 1 2 t

Algorithm size()return t + 1

Algorithm pop()if isEmpty() then

throw EmptyStackException else

t t 1return S[t + 1]

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 1010

Array-based Stack (cont.)Array-based Stack (cont.)The array storing the The array storing the stack elements may stack elements may become fullbecome fullA push operation will A push operation will then throw a then throw a FullStackExceptionFullStackException– Limitation of the Limitation of the

array-based array-based implementationimplementation

– Not intrinsic to the Not intrinsic to the Stack ADTStack ADT

S0 1 2 t

Algorithm push(o)if t = S.length 1 then

throw FullStackException else

t t + 1S[t] o

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 1111

Performance and LimitationsPerformance and Limitations

PerformancePerformance– Let Let nn be the number of elements in the stack be the number of elements in the stack– The space used is The space used is OO((nn))

– Each operation runs in time Each operation runs in time OO(1)(1)

LimitationsLimitations– The maximum size of the stack must be The maximum size of the stack must be

defined a priori and cannot be changeddefined a priori and cannot be changed– Trying to push a new element into a full stack Trying to push a new element into a full stack

causes an implementation-specific exceptioncauses an implementation-specific exception

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 1212

Array-based Stack in JavaArray-based Stack in Java

public class ArrayStackimplements Stack {

// holds the stack elements private Object S[ ];

// index to top elementprivate int top = -1;

// constructorpublic ArrayStack(int capacity) {

S = new Object[capacity]); }

public Object pop()throws EmptyStackException {

if isEmpty()throw new EmptyStackException

(“Empty stack: cannot pop”);Object temp = S[top];// facilitates garbage collection S[top] = null;top = top – 1;return temp;

}

……

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 1313

Parentheses MatchingParentheses Matching

Each “(”, “{”, or “[” must be paired Each “(”, “{”, or “[” must be paired with a matching “)”, “}”, or “[”with a matching “)”, “}”, or “[”– correct: correct: ( )(( ))( )(( )){{([( )])([( )])}}– correct: correct: ((( )(( ))((( )(( )){{([( )])([( )])}}– incorrect: incorrect: )(( )))(( )){{([( )])([( )])}}– incorrect: incorrect: (({{[ ])[ ])}}– incorrect: incorrect: ((

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 1414

Parentheses Matching AlgorithmParentheses Matching AlgorithmAlgorithm Algorithm ParenMatchParenMatch((XX,,nn))::Input:Input: An array An array X X of of n n tokens, each of which is either a grouping symbol, atokens, each of which is either a grouping symbol, avariable, an arithmetic operator, or a numbervariable, an arithmetic operator, or a numberOutput:Output: true true if and only if all the grouping symbols in if and only if all the grouping symbols in X X matchmatchLet Let S S be an empty stackbe an empty stackfor for ii==0 to 0 to nn--1 1 dodo

if if XX[[ii] ] is an opening grouping symbol is an opening grouping symbol thenthenSS..pushpush((XX[[ii]]))

else if else if XX[[ii] ] is a closing grouping symbol is a closing grouping symbol thenthenif if SS..isEmptyisEmpty() () thenthen

return false return false {{nothing to match withnothing to match with} } if if SS..poppop() does not match the type of () does not match the type of XX[[ii] ] thenthen

return false return false {{wrong typewrong type} } if if SS..isEmptyisEmpty() () thenthen

return true return true {{every symbol matchedevery symbol matched} } elseelse

return false return false {{some symbols were never matchedsome symbols were never matched}}

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 1515

HTML Tag MatchingHTML Tag Matching

<body><body><center><center><h1> The Little Boat </h1><h1> The Little Boat </h1></center></center><p> The storm tossed the little<p> The storm tossed the littleboat like a cheap sneaker in anboat like a cheap sneaker in anold washing machine. The threeold washing machine. The threedrunken fishermen were used todrunken fishermen were used tosuch treatment, of course, butsuch treatment, of course, butnot the tree salesman, who even asnot the tree salesman, who even asa stowaway now felt that hea stowaway now felt that hehad overpaid for the voyage. </p>had overpaid for the voyage. </p><ol><ol><li> Will the salesman die? </li><li> Will the salesman die? </li><li> What color is the boat? </li><li> What color is the boat? </li><li> And what about Naomi? </li><li> And what about Naomi? </li></ol></ol></body></body>

The Little BoatThe Little Boat

The storm tossed the little boatThe storm tossed the little boatlike a cheap sneaker in an oldlike a cheap sneaker in an oldwashing machine. The threewashing machine. The threedrunken fishermen were used todrunken fishermen were used tosuch treatment, of course, but notsuch treatment, of course, but notthe tree salesman, who even asthe tree salesman, who even asa stowaway now felt that he hada stowaway now felt that he hadoverpaid for the voyage.overpaid for the voyage.

1. Will the salesman die?1. Will the salesman die?2. What color is the boat?2. What color is the boat?3. And what about Naomi?3. And what about Naomi?

For fully-correct HTML, each <name> should pair with a matching For fully-correct HTML, each <name> should pair with a matching </name></name>

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 1616

Tag Matching AlgorithmTag Matching AlgorithmIs similar to parentheses matching:Is similar to parentheses matching:import import java.util.StringTokenizer;java.util.StringTokenizer;import import datastructures.Stack;datastructures.Stack;import import datastructures.NodeStack;datastructures.NodeStack;import import java.io.*;java.io.*;/** Simpli.ed test of matching tags in an HTML document. *//** Simpli.ed test of matching tags in an HTML document. */public class public class HTML HTML { { /** Nested class to store simple HTML tags *//** Nested class to store simple HTML tags */

public static class public static class Tag Tag { { String name; // The name of this tagString name; // The name of this tagboolean boolean opening; // Is true i. this is an opening tagopening; // Is true i. this is an opening tagpublic public Tag() Tag() { { // Default constructor// Default constructor

name = "";name = "";opening = opening = falsefalse;;

}}public public Tag(String nm, Tag(String nm, boolean boolean op) op) { { // Preferred constructor// Preferred constructorname = nm;name = nm;opening = op;opening = op;}}/** Is this an opening tag? *//** Is this an opening tag? */public boolean public boolean isOpening() isOpening() { { return return opening; opening; } } /** Return the name of this tag *//** Return the name of this tag */public public String getName() String getName() {{return return name; name; }}

}}/** Test if every opening tag has a matching closing tag. *//** Test if every opening tag has a matching closing tag. */public boolean public boolean isHTMLMatched(Tag[ ] tag) isHTMLMatched(Tag[ ] tag) { {

Stack S = Stack S = new new NodeStack(); // Stack for matching tagsNodeStack(); // Stack for matching tagsfor for ((int int i=0; (ii=0; (i<<tag.length) && (tag[i] != tag.length) && (tag[i] != nullnull); i++) ); i++) { {

if if (tag[i].isOpening())(tag[i].isOpening())S.push(tag[i].getName()); // opening tag; push its name on the stackS.push(tag[i].getName()); // opening tag; push its name on the stackelse else { {

if if (S.isEmpty()) // nothing to match(S.isEmpty()) // nothing to matchreturn falsereturn false;;

if if (!((String) S.pop()).equals(tag[i].getName())) // wrong match(!((String) S.pop()).equals(tag[i].getName())) // wrong matchreturn falsereturn false;;

}}} } if if (S.isEmpty())(S.isEmpty())

return truereturn true; // we matched everything; // we matched everythingreturn falsereturn false; // we have some tags that never were matched; // we have some tags that never were matched

}}

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 1717

Tag Matching Algorithm, cont.Tag Matching Algorithm, cont. public final static int public final static int CAPACITY = 1000;CAPACITY = 1000; // Tag array size upper bound// Tag array size upper bound /* Parse an HTML document into an array of html tags *//* Parse an HTML document into an array of html tags */ public public Tag[ ] parseHTML(BufferedReader r) Tag[ ] parseHTML(BufferedReader r) throws throws IOException {IOException { String line;String line; // a line of text// a line of text booleanboolean inTag = inTag = falsefalse ;; // true iff we are in a tag// true iff we are in a tag Tag[ ] tag = Tag[ ] tag = new new Tag[CAPACITY]; // our tag array (initially all null)Tag[CAPACITY]; // our tag array (initially all null) int int count = 0count = 0 ;; // tag counter// tag counter while while ((line = r.readLine()) != ((line = r.readLine()) != nullnull) {) {

// Create a string tokenizer for HTML tags (use < and > as delimiters)// Create a string tokenizer for HTML tags (use < and > as delimiters)StringTokenizer st = StringTokenizer st = new new StringTokenizer(line,"<> \t",StringTokenizer(line,"<> \t",truetrue););while while (st.hasMoreTokens()) {(st.hasMoreTokens()) {

String token = (String) st.nextToken();String token = (String) st.nextToken();if if (token.equals("<")) // opening a new HTML tag(token.equals("<")) // opening a new HTML tag

inTag = inTag = truetrue;;else if else if (token.equals(">")) // ending an HTML tag(token.equals(">")) // ending an HTML tag

inTag = inTag = falsefalse;;else if else if (inTag) { // we have a opening or closing HTML tag(inTag) { // we have a opening or closing HTML tag

if if ( (token.length() == 0) | | (token.charAt(0) != ’/’) )( (token.length() == 0) | | (token.charAt(0) != ’/’) )tag[count++] = tag[count++] = new new Tag(token, Tag(token, truetrue); // opening tag); // opening tag

else else // ending tag// ending tagtag[count++] = tag[count++] = new new Tag(token.substring(1), Tag(token.substring(1),

falsefalse); // skip the ); // skip the } // Note: we ignore anything not in an HTML tag} // Note: we ignore anything not in an HTML tag

}}}}return return tag; // our array of tagstag; // our array of tags

}} /** Tester method *//** Tester method */ public static void public static void main(String[ ] args) main(String[ ] args) throws throws IOException {IOException { BufferedReader stdr;BufferedReader stdr; // Standard Input Reader// Standard Input Reader stdr = stdr = new new BufferedReader(BufferedReader(new new InputStreamReader(System.in));InputStreamReader(System.in)); HTML tagChecker = HTML tagChecker = new new HTML();HTML(); if if (tagChecker.isHTMLMatched(tagChecker.parseHTML(stdr)))(tagChecker.isHTMLMatched(tagChecker.parseHTML(stdr)))

System.out.println("The input file is a matched HTML document.");System.out.println("The input file is a matched HTML document."); elseelse

System.out.println("The input file is not a matched HTML document.");System.out.println("The input file is not a matched HTML document."); }}}}

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 1818

Computing SpansComputing SpansWe show how to use a We show how to use a stack as an auxiliary data stack as an auxiliary data structure in an algorithmstructure in an algorithmGiven an an array Given an an array XX, the , the span span SS[[ii]] of of XX[[ii]] is the is the maximum number of maximum number of consecutive elements consecutive elements XX[[jj] ] immediately preceding immediately preceding XX[[ii] ] and such that and such that XX[[jj] ] XX[[ii]] Spans have applications Spans have applications to financial analysisto financial analysis– E.g., stock at 52-week highE.g., stock at 52-week high 66 33 44 55 22

11 11 22 33 11

X

S

01234567

0 1 2 3 4

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 1919

Quadratic AlgorithmQuadratic Algorithm

AlgorithmAlgorithm spans1spans1((X, nX, n))InputInput array array XX of of nn integers integersOutputOutput array array SS of spans of of spans of XX ##

SS new array of new array of nn integers integers nnforfor ii 00 toto nn 1 1 dodo nn

ss 1 1 nnwhile while s s ii XX[[i i ss]] XX[[ii]] 1 1 2 2 …… ( (nn 1) 1)

ss ss 1 1 1 1 2 2 …… ( (nn 1) 1)SS[[ii]] ss nn

returnreturn S S 11

Algorithm Algorithm spans1 spans1 runs in runs in OO((nn22) ) time time

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 2020

Computing Spans with a StackComputing Spans with a StackWe keep in a stack the We keep in a stack the indices of the elements indices of the elements visible when “looking visible when “looking back”back”

We scan the array from We scan the array from left to rightleft to right– Let Let i i be the current indexbe the current index– We pop indices from the We pop indices from the

stack until we find index stack until we find index jj such that such that XX[[ii]] X X[[jj]]

– We set We set SS[[ii]] i i j j– We push We push xx onto the stack onto the stack

01234567

0 1 2 3 4 5 6 7

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 2121

Linear AlgorithmLinear Algorithm

AlgorithmAlgorithm spans2spans2((X, nX, n)) ##SS new array of new array of nn integers integers nnAA new empty stacknew empty stack 11

forfor ii 00 toto nn 1 1 dodo nnwhilewhile ((AA..isEmptyisEmpty() ()

XX[[A.topA.top()]()] XX[[ii] )] ) dodonnA.popA.pop()() nn

if if AA..isEmptyisEmpty()() thenthen nnSS[[ii]] i i 11 nn

elseelse SS[[ii]] i i A.top A.top()() nn

AA..pushpush((ii)) nnreturnreturn S S 11

Each index of the Each index of the arrayarray– Is pushed into the Is pushed into the

stack exactly once stack exactly once – Is popped from the Is popped from the

stack at most oncestack at most once

The statements in The statements in the while-loop are the while-loop are executed at most executed at most nn times times Algorithm Algorithm spans2 spans2 runs in runs in OO((nn) ) time time

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 2222

The Queue ADTThe Queue ADTThe The QueueQueue ADT stores ADT stores arbitrary objectsarbitrary objects

Insertions and deletions Insertions and deletions follow the first-in first-out follow the first-in first-out schemescheme

Insertions are at the rear of Insertions are at the rear of the queue and removals are the queue and removals are at the front of the queueat the front of the queue

Main queue operations:Main queue operations:– enqueueenqueue(object): inserts an (object): inserts an

element at the end of the element at the end of the queuequeue

– object object dequeuedequeue(): removes (): removes and returns the element at and returns the element at the front of the queuethe front of the queue

Auxiliary queue Auxiliary queue operations:operations:– object object frontfront(): returns the (): returns the

element at the front element at the front without removing itwithout removing it

– integer integer sizesize(): returns the (): returns the number of elements storednumber of elements stored

– boolean boolean isEmptyisEmpty(): (): indicates whether no indicates whether no elements are storedelements are stored

ExceptionsExceptions– Attempting the execution Attempting the execution

of dequeue or front on an of dequeue or front on an empty queue throws an empty queue throws an EmptyQueueExceptionEmptyQueueException

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 2323

Queue ExampleQueue ExampleOperationOperation OutputOutput Q Q enqueueenqueue((55)) –– ((55))enqueueenqueue((33)) –– ((55, , 33))dequeuedequeue()() 55 ((33))enqueueenqueue((77)) –– ((33, , 77))dequeuedequeue()() 33 ((77))frontfront()() 77 ((77))dequeuedequeue()() 77 ()()dequeuedequeue()() “error”“error” ()()isEmptyisEmpty()() truetrue ()()enqueueenqueue((99)) –– ((99))enqueueenqueue((77)) –– ((99, , 77))sizesize(()) 22 ((99, , 77))enqueueenqueue((33)) –– ((99, , 77, , 33))enqueueenqueue((55)) –– ((99, , 77, , 33, , 55))dequeuedequeue()() 99 ((77, , 33, , 55))

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 2424

Applications of QueuesApplications of Queues

Direct applicationsDirect applications– Waiting lists, bureaucracyWaiting lists, bureaucracy– Access to shared resources (e.g., Access to shared resources (e.g.,

printer)printer)– MultiprogrammingMultiprogramming

Indirect applicationsIndirect applications– Auxiliary data structure for algorithmsAuxiliary data structure for algorithms– Component of other data structuresComponent of other data structures

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 2525

Array-based QueueArray-based QueueUse an array of size Use an array of size NN in a circular fashion in a circular fashionTwo variables keep track of the front and rearTwo variables keep track of the front and rearff index of the front elementindex of the front elementrr index immediately past the rear elementindex immediately past the rear element

Array location Array location rr is kept empty is kept empty

Q0 1 2 rf

normal configuration

Q0 1 2 fr

wrapped-around configuration

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 2626

Queue OperationsQueue Operations

We use the We use the modulo operator modulo operator (remainder of (remainder of division)division)

Algorithm size()return (N f + r) mod N

Algorithm isEmpty()return (f r)

Q0 1 2 rf

Q0 1 2 fr

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 2727

Queue Operations (cont.)Queue Operations (cont.)Algorithm enqueue(o)

if size() = N 1 thenthrow FullQueueException

else Q[r] or (r + 1) mod N

Operation enqueue Operation enqueue throws an exception throws an exception if the array is fullif the array is fullThis exception is This exception is implementation-implementation-dependentdependent

Q0 1 2 rf

Q0 1 2 fr

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 2828

Queue Operations (cont.)Queue Operations (cont.)Operation dequeue Operation dequeue throws an exception throws an exception if the queue is if the queue is emptyemptyThis exception is This exception is specified in the specified in the queue ADTqueue ADT

Algorithm dequeue()if isEmpty() then

throw EmptyQueueException else

o Q[f]f (f + 1) mod Nreturn o

Q0 1 2 rf

Q0 1 2 fr

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 2929

Queue Interface in JavaQueue Interface in JavaJava interface Java interface corresponding to corresponding to our Queue ADTour Queue ADT

Requires the Requires the definition of class definition of class EmptyQueueExceptionEmptyQueueExceptionNo corresponding No corresponding built-in Java classbuilt-in Java class

public interface Queue {

public int size();

public boolean isEmpty();

public Object front()throws EmptyQueueException;

public void enqueue(Object o);

public Object dequeue() throws EmptyQueueException;

}

Stacks and QueuesStacks and Queues CSC311: Data StructuresCSC311: Data Structures 3030

Application: Round Robin Application: Round Robin SchedulersSchedulers

We can implement a round robin scheduler using We can implement a round robin scheduler using a queue, a queue, QQ, by repeatedly performing the , by repeatedly performing the following steps:following steps:

1.1. e = Q.e = Q.dequeue()dequeue()

2.2. Service element Service element ee

3.3. Q.Q.enqueue(enqueue(ee))The Queue

Shared

Service

1 . Deque the

next element

3 . Enqueue the

serviced element

2 . Service the

next element