Vous êtes sur la page 1sur 41

CS 270

Algorithms

Week 6 Oliver
Kullmann

Dynamic
sets
Data structures Simple
implementa-
tion
1 Dynamic sets Special
cases

2 Simple implementation Stacks

Implementatio
3 Special cases Queues

Implementatio
4 Stacks Tutorial

5 Implementation
6 Queues
7 Implementation
8 Tutorial
CS 270
General remarks Algorithms

Oliver
Kullmann

Dynamic
sets

Simple
We start considering Part III “Data Structures” from implementa-
tion
CLRS. Special
cases
As a first example we consider two special cases of
Stacks
“buffers”, namely stacks and queues. Implementatio

Queues
Reading from CLRS for week 5 Implementatio

The introduction to Part III on using sets on a computer. Tutorial

Chapter 10, Section 10.1.


CS 270
Sets Algorithms

The most fundamental mathematical notion is that of a set: Oliver


Kullmann

We have the possibility to determine the elements of a set. Dynamic


sets
And we can form sets, either by some set-defining property,
Simple
or by using already given sets (e.g., unions, intersections, implementa-
tion
differences).
Special
cases
Now to bring the eternal and infinite world of mathematics to a
Stacks
computer, we need to take care of
Implementatio

construction of “objects” Queues

destruction of “objects” Implementatio

naming (basically of functions) Tutorial

order issues (sets are unordered, but in computation there is


always order).
For this, CLRS uses the (generic) ADT of “dynamic sets”.

ADT: “abstract data type” —


values (like “sets”) and how to operate with them.
CS 270
Elements of a dynamic sets Algorithms

A “dynamic set” might contain Oliver


Kullmann

pointers (or iterators) to objects, Dynamic


or the objects themselves (in Java this can be only integers sets

Simple
and other primitive types, in C++ this is possible for every implementa-
tion
type of object).
Special
Whatever the objects in a set are, access to them (especially for cases

Stacks
changing them) is only possible via a pointer (or iterator).
Implementatio

For insertion into a dynamic set, we must be given the Queues

object itself, and typically we obtain the pointer (iterator, Implementatio

handle) to the copy of that object in the dynamic set back. Tutorial

For deletion from a dynamic set, we typically have the


pointer of an object (already) in the dynamic set, and we
want to delete that (very specific) object.
For searching, we typically have only given some “key
information”, and we want to search for some element in the
dynamic set, which fits this (key) information.
CS 270
Keys Algorithms

Oliver
Kullmann

Dynamic
sets
Besides objects (which become “elements” once they are in the
Simple
set) and pointers, CLRS uses the notion of a key to identify an implementa-
tion
object:
Special
cases
If the object is for example a record of personal attributes, Stacks
then the name or some form of ID can be used as a key. Implementatio

Queues

Often they keys are used for sorting. Implementatio

Tutorial

For example for that database of personal attributes,


we might sort it according to alphabetical sorting of names.
CS 270
Dynamic sets: elementship and search Algorithms

Oliver
With sets S we can “ask” whether “x ∈ S” is true. This is the Kullmann

most basic set operation, and the equivalent for dynamic sets is Dynamic
sets
the operation
Simple
implementa-
SEARCH(S, k) for key k and dynamic set S, returning tion

either a pointer (iterator) to an object in S with key k, or Special


cases
NIL if there is no such object. Stacks

Implementatio
We require the ability to extract the key from an object in S, Queues
and to compare keys for equality. Implementatio

Tutorial
1 Storing S via an array (or a list), SEARCH can be
performed in O(|S|) time (that is, linear time) by simple
sequential search.
2 To do faster than this, typically in time O(log(|S|))
(logarithmic time), under various circumstances, is a major
aim of data structures for dynamic sets.
CS 270
Dynamic sets: modifying operations Algorithms

Oliver
With the following operations we can build and change dynamic Kullmann

sets: Dynamic
sets

INSERT(S, x) inserts an object into dynamic set S, where Simple


implementa-
x is either a pointer or the object itself. tion

Special
DELETE(S, x) deletes an object from dynamic set S, cases

where here x is a pointer (iterator) into S. Stacks

Implementatio
Note that the “x” in DELETE is of a different nature than the Queues
“x” in INSERT: It is a pointer (iterator!) into the (dynamic) Implementatio
set (and thus these two x are of different type). Tutorial

The most important application of INSERT is for creating a


dynamic set:
To create a set S of size n, call INSERT(S, −) n-times.

We always have INSERT, while we might not have DELETE.


CS 270
Dynamic sets: using order Algorithms

Oliver
Kullmann
Often it is assumed that a linear order is given on the keys:
Dynamic
So besides “k == k ′ ?” sets

Simple
we now can ask “k ≤ k ′ ?”. implementa-
tion

Special
In practice using strict orders “<” is more common, however cases
this creates some (necessary) technical complications, which in Stacks
this module we won’t be much concerned about (we discuss Implementatio

issues when the need arises). Queues

Implementatio
(These complications have to do with the notion of “equality”, since
Tutorial
“<” includes “not equal”. Considering Java, recall that there (lacking
operator overloading and lacking the ability to distinguish between
“object” and “pointer”) you have two operations for checking
“equality”: “= =” for object-identity and “.equals()” for
object-equality, and now we needed appropriate object-equality
(consistent with the algorithms).)
CS 270
Dynamic sets: four further operations Algorithms

Oliver
Kullmann
Given a linear order on the objects (to be put into the set), we
Dynamic
have the following additional operations: sets

Simple
MINIMUM(S) returns a pointer (iterator) to the element implementa-
tion
with the smallest key Special
cases
MAXIMUM(S) returns a pointer (iterator) to the element
Stacks
with the largest key Implementatio
SUCCESSOR(S, x), where x is a pointer (iterator) into Queues

S, returns the next element in S w.r.t. the order on the keys Implementatio

PREDECESSOR(S, x), where x is a pointer (iterator) Tutorial

into S, returns the previous element in S.

Operations for computing successors and predecessors can fail


(there is no successor resp. predecessor iff we are already at the
end resp. beginning), and in such cases we return NIL.
CS 270
Using sorting algorithms: static case Algorithms

Oliver
Dynamic sets can be realised using sorting, where we have to Kullmann

assume a linear order on the keys. Dynamic


sets
If the set S with n elements is to be built only once, at the Simple
implementa-
beginning, from a sequence of elements, then storing the tion
elements in an array and sorting them, using for example Special
cases
MERGE-SORT with time complexity O(n · log n), is a good
Stacks
option:
Implementatio

SEARCH then takes time O(log n) (using binary search) Queues

Implementatio
while each of MINIMUM, MAXIMUM,
Tutorial
SUCCESSOR, PREDECESSOR takes constant time.

However we are concerned here with the dynamic case, where


insertions and deletions are used in unpredictable ways. If we
not assume that building the set is done (once and for all) at the
beginning, but we want to have insertion and deletion, then the
case is much less favourable.
CS 270
Using sorting algorithms: dynamic case Algorithms

Oliver
Now INSERTION and DELETION take time Kullmann

O(log(n) + n) = O(n), searching first for the right Dynamic


insertion/deletion place, and then shifting the other sets

Simple
elements appropriately, implementa-
tion
while the five other (non-modifying) operations still take
Special
logarithmic resp. constant time. cases

Stacks

For practical applications, the linear complexity of insertion and Implementatio

deletion is not acceptable. And we also see that most of the Queues

intelligence of sophisticated searching algorithms is blown out of Implementatio

the window, and only some form of INSERTION-SORT (in Tutorial

combination with binary search) survived.


It could be said that data structures for dynamic sets try to
introduce some of the intelligent methods into the dynamic
framework, making insertion and deletion more efficient
(necessarily at the cost of making the other operations
(somewhat) less efficient).
CS 270
Special cases of dynamic sets Algorithms

Oliver
Often not all of the operations for dynamic sets are needed, Kullmann

opening up the possibilities of specialised and more efficient Dynamic


implementations. Three important cases are as follows: sets

Simple
implementa-
Buffer Only INSERTION, tion

SHOW-SELECTED-ELEMENT (like Special


cases
MINIMUM and MAXIMUM, but not
Stacks
necessarily related to some order) and
Implementatio
DELETE-SELECTED-ELEMENT; special Queues
cases are “stacks” and “queues”. Implementatio

Priority queue Only INSERTION, MINIMUM resp. Tutorial

MAXIMUM (for min- resp. max-priority queues)


and DELETE-MIN resp. DELETE-MAX
(special queues, where the selected element is
given by a linear order on the keys).
Dictionary Only INSERTION, DELETION and
SEARCH (i.e., no order-requirements).
CS 270
Special cases of dynamic sets (cont.) Algorithms

Oliver
Kullmann

Dynamic
In other words: sets

Simple
implementa-
Buffers (stacks, queues, and priority queues) have the tion

notion of a “selected element”, which they can show and Special


cases
delete (but general deletion is not possible); searching in Stacks
the general sense is not possible. Implementatio

Dictionaries can perform arbitrary deletions and searches, Queues

but they have no order on the elements (and thus also no Implementatio

“special elements”). Tutorial

Insertion is always possible (given that there is enough space).


CS 270
Last in – first out Algorithms

Oliver
Kullmann

Dynamic
sets

Simple
A stack is a buffer where the selected element implementa-
tion
is the element last entered.
Special
cases

Stacks

Thus a stack is characterised by the slogan Implementatio

Queues
“last in – first out” LIFO.
Implementatio
One could also say “first in – last out” (FILO). Tutorial

So if you enter numbers 1, 2, 3 into a stack (in that order), then


you get back 3, 2, 1 (in that order).
CS 270
Stack operations: PUSH, POP, TOP Algorithms

Oliver
Kullmann

For dynamic sets in general we talk about INSERT, but Dynamic


for stacks this is called PUSH. sets

Simple
And the DELETE operation (which here deletes a implementa-
tion
selected element) is called POP.
Special
The operation for returning the selected element is called cases

Stacks
TOP.
Implementatio

Queues
In the book the operation POP combines the above POP (just
Implementatio
deleting the selected element) and the above TOP (just
Tutorial
returning the selected element), which is the old style for a
stack, which has been shown to have severe disadvantages:

Amongst others, separation of concerns requires that we have


two different operations POP and TOP.
CS 270
Examples Algorithms

Oliver
Kullmann
If we have a stack, and perform (in this order)
Dynamic
sets
PUSH(1), PUSH(2), PUSH(3), Simple
implementa-
tion
then TOP yields 3. Special
cases
1 After POP then TOP yields 2. Stacks

2 And after another POP then TOP yields 1. Implementatio

Queues
3 A final POP yields an empty stack. Implementatio

Tutorial
Note that we have precisely as many PUSH as POP
instructions (that holds for every buffer).

What happens if on an empty stack we use


POP or TOP ?!?
CS 270
The EMPTY operation Algorithms

Oliver
Kullmann

Dynamic
In order to check whether the stack is empty, the fourth sets

stack-operation is EMPTY, returning a boolean which is true if Simple


implementa-
and only if the stack is empty. tion

Special
It depends on the concrete stack-implementation (i.e., on cases

Stacks
the interface) what happens in case of an error.
Implementatio
There are two principle error possibilities: stack overflow Queues
and stack underflow. Implementatio

Overflow means that a push-operation exceeds the Tutorial

stack-capacity.
Underflow means the use of a top- or pop-operation on an
empty stack.
CS 270
Implementation via an array Algorithms

Oliver
Kullmann

Dynamic
sets
Using an array we can easily implement the ADT Stack: Simple
implementa-
tion
1 The class (Java or, say, C++) contains as data member
Special
(“instance variable”) a fixed-size array. cases

2 We fill that array from the left. Stacks

Implementatio
3 An index-variable points to the currently open slot in the
Queues
array. Implementatio
4 Popping an element from the stack just means Tutorial

decrementing that index.

We consider an implementation via the Java-class Stack.


CS 270
Class Stack Algorithms

Oliver
Kullmann
c l a s s Stack {
Dynamic
private f i n a l int [ ] stack ; sets

p r i v a t e f i n a l i n t N ; // max number e l e m e n t s Simple


implementa-
p r i v a t e i n t n ; // number o f e l e m e n t s tion

Special
cases
public Stack ( f i n a l i n t N ) { Stacks
// S t a n d a r d e x c e p t i o n s r a i s e d i f N < 0 Implementatio
// o r N i s t o o b i g f o r a v a i l a b l e memory . Queues
N = N ; Implementatio

s t a c k = new i n t [ N ] ; Tutorial

n = 0;
}

Remark: Note that n is the current number of elements as well


as the index of the next open array-slot.
CS 270
Class Stack (cont.) Algorithms

Oliver
p u b l i c boolean empty ( ) { r e t u r n n==0; } Kullmann

Dynamic
sets
public i n t top ( ) {
Simple
// S t a n d a r d e x c e p t i o n r a i s e d i f n == 0 . implementa-
tion
a s s e r t ( s t a c k != n u l l && s t a c k . l e n g t h==N) ;
Special
a s s e r t ( n >= 0 && n <= N) ; cases

return stack [ n −1]; Stacks

} Implementatio

Queues

Remark: assert is here used for conditions which are enforced Implementatio

by the internal logic of the class (and thus a violation would Tutorial

show that there is a bug in the class definition).


The case n == 0 is absolutely possible according to the logic of
the class Stack: Either the caller has to ensure that this never
happens, or the exception has to be handled.
CS 270
Class Stack (cont.) Algorithms

p u b l i c boolean push ( f i n a l i n t x ) { Oliver


Kullmann
a s s e r t ( n >= 0 && n <= N) ;
i f ( n == N) r e t u r n f a l s e ; Dynamic
sets
a s s e r t ( s t a c k != n u l l && s t a c k . l e n g t h==N) ; Simple
s t a c k [ n++] = x ; implementa-
tion
return true ; Special
} cases

Stacks
p u b l i c boolean pop ( ) {
Implementatio
a s s e r t ( n >= 0 ) ;
Queues
a s s e r t ( n <= N) ;
Implementatio
i f ( n == 0 ) r e t u r n f a l s e ; Tutorial
−−n ;
return true ;
}
Remarks: push and pop don’t throw (exceptions). Both
operations can fail (if we have already N elements, or there is no
element left), in which case they return false .
CS 270
Class Stack (cont.) Algorithms

Oliver
Kullmann
// a d d i t i o n a l f u n c t i o n a l i t y :
public int s i z e () { return n ; } Dynamic
sets
public i n t max size ( ) { return N; } Simple
implementa-
tion
p u b l i c boolean e q u a l s ( S t a c k S ) { Special
i f ( n != S . n ) r e t u r n f a l s e ; cases

f o r ( i n t i = 0 ; i < n ; ++i ) Stacks

i f ( s t a c k [ i ] != S . s t a c k [ i ] ) Implementatio

Queues
return f a l s e ;
Implementatio
return true ;
Tutorial
}

Remark: Recall that for Stack-variables a, b the comparison


a == b checks whether these pointers are equal — if we wish
to check for equal content we need to use a. equals(b).
CS 270
Class Stack (cont.) Algorithms

Oliver
Kullmann

public String toString () { Dynamic


sets
S t r i n g o u t = ” [ ” + n + ” , ” + N + ” ] \ n” ; Simple
f o r ( i n t i = 0 ; i < n −1; ++i ) implementa-
tion
o u t += s t a c k [ i ] + ” ” ; Special
cases
i f ( n > 0 ) o u t += s t a c k [ n − 1 ] ;
Stacks
return out ;
Implementatio
}
Queues

Implementatio
} Tutorial

Remark: Here we take care to avoid a trailing space (after the


last stack element).
CS 270
First in – first out Algorithms

Oliver
Kullmann

Dynamic
sets

A queue is a buffer where the selected element Simple


implementa-
is the element first entered. tion

Special
cases

Stacks
Thus a queue is characterised by the slogan Implementatio
“first in – first out” FIFO. Queues

One could also say “last in – last out” (“LILO”), but that Implementatio

is apparently not used. Tutorial

So if you enter numbers 1, 2, 3 into a queue (in that order), then


you get back 1, 2, 3 (in that order).
CS 270
Queue operations Algorithms

Oliver
Kullmann

Dynamic
sets

We will use very similar notions as for stacks: Simple


implementa-
tion

The only difference is that instead of TOP we use Special


cases
FRONT.
Stacks
Besides that we have PUSH, POP, EMPTY. Implementatio

The book uses ENQUEUE instead of PUSH, and Queues

DEQUEUE instead of POP. Implementatio

Tutorial
However our choice is more popular with programming
languages.
CS 270
Examples Algorithms

Oliver
Kullmann

Dynamic
sets
If we have a queue, and perform (in this order)
Simple
implementa-
tion
PUSH(1), PUSH(2), PUSH(3),
Special
cases
then FRONT yields 1. Stacks

Implementatio
1 After POP then FRONT yields 2.
Queues
2 And after another POP then FRONT yields 3. Implementatio

3 A final POP yields an empty queue. Tutorial

Note that we have precisely as many PUSH as POP


instructions (that holds for every buffer).
CS 270
Implementation via an array Algorithms

Oliver
Kullmann
Using an array we can (relatively) easily implement the ADT
Queue: Dynamic
sets

1 The class (Java or, say, C++) contains as data member Simple
implementa-
(instance variable) a fixed-size array. tion

Special
2 We have furthermore index-variables for the left (“head”) cases

and the right (“tail”) end. Stacks

Implementatio
3 PUSH moves forward the right end, POP the left end.
Queues
4 We do not need to re-allocate the elements, when we reach Implementatio
the right boundary of the array while actually not the whole Tutorial
array is filled, since we can “wrap around” the part of the
array used for the queue.
5 For a real implementation, one needs to get the details
right, but the basic idea is very simple.

We consider an implementation via the Java-class Queue.


CS 270
Class Queue Algorithms

Oliver
Kullmann

c l a s s Queue { Dynamic
p r i v a t e f i n a l i n t [ ] queue ; sets

p r i v a t e f i n a l i n t N ; // maximal number Simple


implementa-
p r i v a t e i n t n ; // number o f e l e m e n t s tion

p r i v a t e i n t a , b ; // f i r s t and one−p a s t −the Special


cases
−l a s t i n d e x o f c u r r e n t e l e m e n t s Stacks

Implementatio

p u b l i c Queue ( f i n a l i n t N ) { Queues

// S t a n d a r d e x c e p t i o n s r a i s e d i f N < 0 o r Implementatio

N i s t o o b i g f o r a v a i l a b l e memory . Tutorial

N = N ;
queue = new i n t [ N ] ;
n = a = b = 0;
}
CS 270
Class Queue (cont.) Algorithms

Oliver
Kullmann

Dynamic
sets

p u b l i c boolean empty ( ) { r e t u r n n==0; } Simple


implementa-
tion

public int front () { Special


cases
// Queue u n d e r f l o w i f n==0 ( n o t d e t e c t e d ) Stacks
a s s e r t ( queue != n u l l && queue . l e n g t h==N) ; Implementatio
a s s e r t ( a >= 0 && a < N) ; Queues
r e t u r n queue [ a ] ; Implementatio

} Tutorial
CS 270
Class Queue (cont.) Algorithms

Oliver
Kullmann

Dynamic
p u b l i c boolean push ( f i n a l i n t x ) { sets

Simple
a s s e r t ( n >= 0 && n <= N) ; implementa-
tion
i f ( n == N) r e t u r n f a l s e ;
Special
a s s e r t ( queue != n u l l && queue . l e n g t h==N) ; cases
a s s e r t ( b >= 0 && b < N) ; Stacks

queue [ b ] = x ; Implementatio

i f ( b == N−1) b = 0 ; e l s e ++b ; Queues

++n ; Implementatio

return true ; Tutorial

}
CS 270
Class Queue (cont.) Algorithms

Oliver
Kullmann

Dynamic
sets

p u b l i c boolean pop ( ) { Simple


implementa-
a s s e r t ( n >= 0 && n <= N) ; tion

i f ( n == 0 ) r e t u r n f a l s e ; Special
cases
a s s e r t ( a >= 0 && a < N) ; Stacks
i f ( a == N−1) a = 0 ; e l s e ++a ; Implementatio
−−n ; Queues
return true ; Implementatio

} Tutorial
CS 270
Class Queue (cont.) Algorithms

Oliver
// a d d i t i o n a l f u n c t i o n a l i t y : Kullmann

public int s i z e () { return n ; } Dynamic


public i n t max size ( ) { return N; } sets

Simple
implementa-
p u b l i c boolean e q u a l s ( Queue S ) { tion

Special
i f ( n != S . n ) r e t u r n f a l s e ; cases
f o r ( i n t i=a , j=S . a , c =0; Stacks

c<n ; Implementatio

i =( i==N−1) ? 0 : i +1, j =( j==N−1) ? 0 : j +1, Queues

++c ) Implementatio

i f ( queue [ i ] != S . queue [ j ] ) Tutorial

return f a l s e ;
return true ;
}

Note that c is used here as a counter.


CS 270
Class Queue (cont.) Algorithms

Oliver
Kullmann

Dynamic
public String toString () { sets

Simple
S t r i n g o u t = ” [ ” + n + ” , ” + N + ” ] \ n” ; implementa-
tion
for ( int i = a , c = 0;
Special
c < n; cases
i = ( i==N−1) ? 0 : i +1, ++c ) Stacks

o u t += queue [ i ] + ” ” ; Implementatio

return out ; Queues

} Implementatio

Tutorial

}
CS 270
Pushing and popping Algorithms

Oliver
Kullmann

Dynamic
From [Sedgewick, Exercise 4.6]: sets

Simple
A letter means push and an asterisk means pop in the following implementa-
tion
sequence. Give the sequence of values returned by the pop Special
operations when this sequence of operations is performed on an cases

initially empty stack: Stacks

Implementatio

Queues
EAS*Y*QUE***ST***IO*N***
Implementatio

Tutorial
Solution:

SYEUQTSAONIE
CS 270
Pushing and popping Algorithms

Oliver
Kullmann

Dynamic
From [Sedgewick, Exercise 4.6]: sets

Simple
A letter means push and an asterisk means pop in the following implementa-
tion
sequence. Give the sequence of values returned by the pop Special
operations when this sequence of operations is performed on an cases

initially empty stack: Stacks

Implementatio

Queues
EAS*Y*QUE***ST***IO*N***
Implementatio

Tutorial
Solution:

SYEUQTSAONIE
CS 270
Checking balancedness Algorithms

Oliver
Develop the idea for a program that reads in a sequence of Kullmann

characters, and determines whether its parentheses, braces, and Dynamic


curly braces are “balanced”. sets

Simple
For example implementa-
tion

Special
( [ { ( [ ] ) ( [ ] ) } ] ) cases

Stacks

is balanced, while Implementatio

Queues

( ( [ { } { } [ ] ) ) ) Implementatio

Tutorial

is not.
Solution:
When you read an opening bracket-symbol, push it onto the
stack, when you read a closing bracket-symbol, check whether
it’s the top-symbol, and pop it.
CS 270
Checking balancedness Algorithms

Oliver
Develop the idea for a program that reads in a sequence of Kullmann

characters, and determines whether its parentheses, braces, and Dynamic


curly braces are “balanced”. sets

Simple
For example implementa-
tion

Special
( [ { ( [ ] ) ( [ ] ) } ] ) cases

Stacks

is balanced, while Implementatio

Queues

( ( [ { } { } [ ] ) ) ) Implementatio

Tutorial

is not.
Solution:
When you read an opening bracket-symbol, push it onto the
stack, when you read a closing bracket-symbol, check whether
it’s the top-symbol, and pop it.
CS 270
Pushing and popping again Algorithms

Oliver
Kullmann

Dynamic
A letter means enqueue and an asterisk means dequeue in the sets

sequence Simple
implementa-
tion

EAS*Y*QUE***ST***IO*N*** Special
cases

Stacks

Give the sequence of values returned by the dequeue operations Implementatio

when this sequence of operations is performed on an initially Queues

empty queue. Implementatio

Tutorial
Solution:

EASYQUESTION
CS 270
Pushing and popping again Algorithms

Oliver
Kullmann

Dynamic
A letter means enqueue and an asterisk means dequeue in the sets

sequence Simple
implementa-
tion

EAS*Y*QUE***ST***IO*N*** Special
cases

Stacks

Give the sequence of values returned by the dequeue operations Implementatio

when this sequence of operations is performed on an initially Queues

empty queue. Implementatio

Tutorial
Solution:

EASYQUESTION
CS 270
A queue via two stacks Algorithms

Oliver
Kullmann

Dynamic
Can we implement a queue using two stacks sets

in an efficient way ?! Simple


implementa-
tion

Special
Solution: the basic idea is − · − = + cases

Stacks
1 Use two stacks, IN and OUT. Implementatio
2 The queue is empty iff both stacks are empty. Queues

3 push(x) : IN.push(x). Implementatio

Tutorial
4 front (): if OUT is not-empty, perform OUT.top(),
otherwise pop everything from IN, push it to OUT, and
then perform OUT.top().
5 pop(): The same as with front , only replacing OUT.top()
with OUT.pop().
CS 270
A queue via two stacks Algorithms

Oliver
Kullmann

Dynamic
Can we implement a queue using two stacks sets

in an efficient way ?! Simple


implementa-
tion

Special
Solution: the basic idea is − · − = + cases

Stacks
1 Use two stacks, IN and OUT. Implementatio
2 The queue is empty iff both stacks are empty. Queues

3 push(x) : IN.push(x). Implementatio

Tutorial
4 front (): if OUT is not-empty, perform OUT.top(),
otherwise pop everything from IN, push it to OUT, and
then perform OUT.top().
5 pop(): The same as with front , only replacing OUT.top()
with OUT.pop().

Vous aimerez peut-être aussi