week 6 oliver dynamic data structures simple special...

41
CS 270 Algorithms Oliver Kullmann Dynamic sets Simple implementa- tion Special cases Stacks Implementatio Queues Implementatio Tutorial Week 6 Data structures 1 Dynamic sets 2 Simple implementation 3 Special cases 4 Stacks 5 Implementation 6 Queues 7 Implementation 8 Tutorial

Upload: others

Post on 20-Apr-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Week 6

Data structures

1 Dynamic sets

2 Simple implementation

3 Special cases

4 Stacks

5 Implementation

6 Queues

7 Implementation

8 Tutorial

Page 2: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

General remarks

We start considering Part III “Data Structures” fromCLRS.

As a first example we consider two special cases of“buffers”, namely stacks and queues.

Reading from CLRS for week 5

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

Chapter 10, Section 10.1.

Page 3: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

SetsThe most fundamental mathematical notion is that of a set:

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

And we can form sets, either by some set-defining property,or by using already given sets (e.g., unions, intersections,differences).

Now to bring the eternal and infinite world of mathematics to acomputer, we need to take care of

construction of “objects”

destruction of “objects”

naming (basically of functions)

order issues (sets are unordered, but in computation there isalways order).

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

ADT: “abstract data type” —values (like “sets”) and how to operate with them.

Page 4: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Elements of a dynamic setsA “dynamic set” might contain

pointers (or iterators) to objects,or the objects themselves (in Java this can be only integersand other primitive types, in C++ this is possible for everytype of object).

Whatever the objects in a set are, access to them (especially forchanging them) is only possible via a pointer (or iterator).

For insertion into a dynamic set, we must be given theobject itself, and typically we obtain the pointer (iterator,handle) to the copy of that object in the dynamic set back.For deletion from a dynamic set, we typically have thepointer of an object (already) in the dynamic set, and wewant to delete that (very specific) object.

For searching, we typically have only given some “keyinformation”, and we want to search for some element in thedynamic set, which fits this (key) information.

Page 5: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Keys

Besides objects (which become “elements” once they are in theset) and pointers, CLRS uses the notion of a key to identify anobject:

If the object is for example a record of personal attributes,then the name or some form of ID can be used as a key.

Often they keys are used for sorting.

For example for that database of personal attributes,we might sort it according to alphabetical sorting of names.

Page 6: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Dynamic sets: elementship and search

With sets S we can “ask” whether “x ∈ S” is true. This is themost basic set operation, and the equivalent for dynamic sets isthe operation

SEARCH(S , k) for key k and dynamic set S , returningeither a pointer (iterator) to an object in S with key k , orNIL if there is no such object.

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

1 Storing S via an array (or a list), SEARCH can beperformed in O(|S |) time (that is, linear time) by simplesequential search.

2 To do faster than this, typically in time O(log(|S |))(logarithmic time), under various circumstances, is a majoraim of data structures for dynamic sets.

Page 7: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Dynamic sets: modifying operations

With the following operations we can build and change dynamicsets:

INSERT(S , x) inserts an object into dynamic set S , wherex is either a pointer or the object itself.

DELETE(S , x) deletes an object from dynamic set S ,where here x is a pointer (iterator) into S .

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

The most important application of INSERT is for creating adynamic set:

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

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

Page 8: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Dynamic sets: using order

Often it is assumed that a linear order is given on the keys:

So besides “k == k ′ ?”

we now can ask “k ≤ k ′ ?”.

In practice using strict orders “<” is more common, howeverthis creates some (necessary) technical complications, which inthis module we won’t be much concerned about (we discussissues when the need arises).

(These complications have to do with the notion of “equality”, since

“<” 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).)

Page 9: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Dynamic sets: four further operations

Given a linear order on the objects (to be put into the set), wehave the following additional operations:

MINIMUM(S) returns a pointer (iterator) to the elementwith the smallest key

MAXIMUM(S) returns a pointer (iterator) to the elementwith the largest key

SUCCESSOR(S , x), where x is a pointer (iterator) intoS , returns the next element in S w.r.t. the order on the keys

PREDECESSOR(S , x), where x is a pointer (iterator)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 theend resp. beginning), and in such cases we return NIL.

Page 10: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Using sorting algorithms: static case

Dynamic sets can be realised using sorting, where we have toassume a linear order on the keys.

If the set S with n elements is to be built only once, at thebeginning, from a sequence of elements, then storing theelements in an array and sorting them, using for exampleMERGE-SORT with time complexity O(n · log n), is a goodoption:

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

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

However we are concerned here with the dynamic case, whereinsertions and deletions are used in unpredictable ways. If wenot assume that building the set is done (once and for all) at thebeginning, but we want to have insertion and deletion, then thecase is much less favourable.

Page 11: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Using sorting algorithms: dynamic case

Now INSERTION and DELETION take timeO(log(n) + n) = O(n), searching first for the rightinsertion/deletion place, and then shifting the otherelements appropriately,

while the five other (non-modifying) operations still takelogarithmic resp. constant time.

For practical applications, the linear complexity of insertion anddeletion is not acceptable. And we also see that most of theintelligence of sophisticated searching algorithms is blown out ofthe window, and only some form of INSERTION-SORT (incombination with binary search) survived.

It could be said that data structures for dynamic sets try tointroduce some of the intelligent methods into the dynamicframework, making insertion and deletion more efficient(necessarily at the cost of making the other operations(somewhat) less efficient).

Page 12: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Special cases of dynamic sets

Often not all of the operations for dynamic sets are needed,opening up the possibilities of specialised and more efficientimplementations. Three important cases are as follows:

Buffer Only INSERTION,SHOW-SELECTED-ELEMENT (likeMINIMUM and MAXIMUM, but notnecessarily related to some order) andDELETE-SELECTED-ELEMENT; specialcases are “stacks” and “queues”.

Priority queue Only INSERTION, MINIMUM resp.MAXIMUM (for min- resp. max-priority queues)and DELETE-MIN resp. DELETE-MAX

(special queues, where the selected element isgiven by a linear order on the keys).

Dictionary Only INSERTION, DELETION andSEARCH (i.e., no order-requirements).

Page 13: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Special cases of dynamic sets (cont.)

In other words:

Buffers (stacks, queues, and priority queues) have thenotion of a “selected element”, which they can show anddelete (but general deletion is not possible); searching inthe general sense is not possible.

Dictionaries can perform arbitrary deletions and searches,but they have no order on the elements (and thus also no“special elements”).

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

Page 14: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Last in – first out

A stack is a buffer where the selected elementis the element last entered.

Thus a stack is characterised by the slogan

“last in – first out” LIFO.

One could also say “first in – last out” (FILO).

So if you enter numbers 1, 2, 3 into a stack (in that order), thenyou get back 3, 2, 1 (in that order).

Page 15: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Stack operations: PUSH, POP, TOP

For dynamic sets in general we talk about INSERT, butfor stacks this is called PUSH.

And the DELETE operation (which here deletes aselected element) is called POP.

The operation for returning the selected element is calledTOP.

In the book the operation POP combines the above POP (justdeleting the selected element) and the above TOP (justreturning the selected element), which is the old style for astack, which has been shown to have severe disadvantages:

Amongst others, separation of concerns requires that we havetwo different operations POP and TOP.

Page 16: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Examples

If we have a stack, and perform (in this order)

PUSH(1),PUSH(2),PUSH(3),

then TOP yields 3.

1 After POP then TOP yields 2.

2 And after another POP then TOP yields 1.

3 A final POP yields an empty stack.

Note that we have precisely as many PUSH as POP

instructions (that holds for every buffer).

What happens if on an empty stack we usePOP or TOP ?!?

Page 17: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

The EMPTY operation

In order to check whether the stack is empty, the fourthstack-operation is EMPTY, returning a boolean which is true ifand only if the stack is empty.

It depends on the concrete stack-implementation (i.e., onthe interface) what happens in case of an error.

There are two principle error possibilities: stack overflow

and stack underflow.

Overflow means that a push-operation exceeds thestack-capacity.

Underflow means the use of a top- or pop-operation on anempty stack.

Page 18: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Implementation via an array

Using an array we can easily implement the ADT Stack:

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

2 We fill that array from the left.

3 An index-variable points to the currently open slot in thearray.

4 Popping an element from the stack just meansdecrementing that index.

We consider an implementation via the Java-class Stack.

Page 19: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Class Stack

c l a s s Stack {pr i va te f i n a l i n t [ ] s t a c k ;pr i va te f i n a l i n t N; // max number e l ement spr i va te i n t n ; // number o f e l ement s

pub l i c Stack ( f i n a l i n t N ) {// Standard e x c e p t i o n s r a i s e d i f N < 0// or N i s too b i g f o r a v a i l a b l e memory .N = N ;s t a c k = new in t [N ] ;n = 0 ;

}

Remark: Note that n is the current number of elements as wellas the index of the next open array-slot.

Page 20: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Class Stack (cont.)

pub l i c boolean empty ( ) { return n==0; }

pub l i c i n t top ( ) {// Standard e x c e p t i o n r a i s e d i f n == 0 .a s s e r t ( s t a c k != nu l l && s ta ck . l e n g t h==N) ;a s s e r t ( n >= 0 && n <= N) ;return s t a c k [ n−1] ;

}

Remark: assert is here used for conditions which are enforcedby the internal logic of the class (and thus a violation wouldshow that there is a bug in the class definition).

The case n == 0 is absolutely possible according to the logic ofthe class Stack: Either the caller has to ensure that this neverhappens, or the exception has to be handled.

Page 21: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Class Stack (cont.)pub l i c boolean push ( f i n a l i n t x ) {

a s s e r t ( n >= 0 && n <= N) ;i f ( n == N) return f a l s e ;a s s e r t ( s t a c k != nu l l && s ta ck . l e n g t h==N) ;s t a c k [ n++] = x ;return true ;

}pub l i c boolean pop ( ) {

a s s e r t ( n >= 0) ;a s s e r t ( n <= N) ;i f ( n == 0) return f a l s e ;−−n ;return true ;

}

Remarks: push and pop don’t throw (exceptions). Bothoperations can fail (if we have already N elements, or there is noelement left), in which case they return false .

Page 22: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Class Stack (cont.)

// a d d i t i o n a l f u n c t i o n a l i t y :pub l i c i n t s i z e ( ) { return n ; }pub l i c i n t max s i z e ( ) { return N; }

pub l i c boolean e qua l s ( Stack S) {i f ( n != S . n ) return f a l s e ;f o r ( i n t i = 0 ; i < n ; ++i )

i f ( s t a c k [ i ] != S . s t a c k [ i ] )return f a l s e ;

return true ;}

Remark: Recall that for Stack-variables a, b the comparisona == b checks whether these pointers are equal — if we wishto check for equal content we need to use a. equals(b).

Page 23: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Class Stack (cont.)

pub l i c S t r i n g t o S t r i n g ( ) {S t r i n g out = ” [ ” + n + ” , ” + N + ” ]\ n” ;f o r ( i n t i = 0 ; i < n−1; ++i )

out += s t a ck [ i ] + ” ” ;i f ( n > 0) out += s t a ck [ n−1] ;return out ;

}

}

Remark: Here we take care to avoid a trailing space (after thelast stack element).

Page 24: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

First in – first out

A queue is a buffer where the selected elementis the element first entered.

Thus a queue is characterised by the slogan

“first in – first out” FIFO.

One could also say “last in – last out” (“LILO”), but thatis apparently not used.

So if you enter numbers 1, 2, 3 into a queue (in that order), thenyou get back 1, 2, 3 (in that order).

Page 25: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Queue operations

We will use very similar notions as for stacks:

The only difference is that instead of TOP we useFRONT.

Besides that we have PUSH, POP, EMPTY.

The book uses ENQUEUE instead of PUSH, andDEQUEUE instead of POP.

However our choice is more popular with programminglanguages.

Page 26: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Examples

If we have a queue, and perform (in this order)

PUSH(1),PUSH(2),PUSH(3),

then FRONT yields 1.

1 After POP then FRONT yields 2.

2 And after another POP then FRONT yields 3.

3 A final POP yields an empty queue.

Note that we have precisely as many PUSH as POP

instructions (that holds for every buffer).

Page 27: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Implementation via an array

Using an array we can (relatively) easily implement the ADTQueue:

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

2 We have furthermore index-variables for the left (“head”)and the right (“tail”) end.

3 PUSH moves forward the right end, POP the left end.

4 We do not need to re-allocate the elements, when we reachthe right boundary of the array while actually not the wholearray is filled, since we can “wrap around” the part of thearray used for the queue.

5 For a real implementation, one needs to get the detailsright, but the basic idea is very simple.

We consider an implementation via the Java-class Queue.

Page 28: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Class Queue

c l a s s Queue {pr i va te f i n a l i n t [ ] queue ;pr i va te f i n a l i n t N; // maximal numberpr i va te i n t n ; // number o f e l ement spr i va te i n t a , b ; // f i r s t and one−past−the

− l a s t i nd e x o f c u r r e n t e l ement s

pub l i c Queue ( f i n a l i n t N ) {// Standard e x c e p t i o n s r a i s e d i f N < 0 or

N i s too b i g f o r a v a i l a b l e memory .N = N ;queue = new in t [N ] ;n = a = b = 0 ;

}

Page 29: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Class Queue (cont.)

pub l i c boolean empty ( ) { return n==0; }

pub l i c i n t f r o n t ( ) {// Queue unde r f l ow i f n==0 ( not d e t e c t e d )a s s e r t ( queue != nu l l && queue . l e n g t h==N) ;a s s e r t ( a >= 0 && a < N) ;return queue [ a ] ;

}

Page 30: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Class Queue (cont.)

pub l i c boolean push ( f i n a l i n t x ) {a s s e r t ( n >= 0 && n <= N) ;i f ( n == N) return f a l s e ;a s s e r t ( queue != nu l l && queue . l e n g t h==N) ;a s s e r t ( b >= 0 && b < N) ;queue [ b ] = x ;i f ( b == N−1) b = 0 ; e l s e ++b ;++n ;return true ;

}

Page 31: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Class Queue (cont.)

pub l i c boolean pop ( ) {a s s e r t ( n >= 0 && n <= N) ;i f ( n == 0) return f a l s e ;a s s e r t ( a >= 0 && a < N) ;i f ( a == N−1) a = 0 ; e l s e ++a ;−−n ;return true ;

}

Page 32: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Class Queue (cont.)

// a d d i t i o n a l f u n c t i o n a l i t y :pub l i c i n t s i z e ( ) { return n ; }pub l i c i n t max s i z e ( ) { return N; }

pub l i c boolean e qua l s (Queue S) {i f ( n != S . n ) return f a l s e ;f o r ( i n t i=a , j=S . a , c=0;

c<n ;i =( i==N−1) ?0 : i +1, j =( j==N−1) ?0 : j +1,

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

return f a l s e ;return true ;

}

Note that c is used here as a counter.

Page 33: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Class Queue (cont.)

pub l i c S t r i n g t o S t r i n g ( ) {S t r i n g out = ” [ ” + n + ” , ” + N + ” ]\ n” ;f o r ( i n t i = a , c = 0 ;

c < n ;i = ( i==N−1) ? 0 : i +1, ++c )

out += queue [ i ] + ” ” ;return out ;

}

}

Page 34: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Pushing and popping

From [Sedgewick, Exercise 4.6]:

A letter means push and an asterisk means pop in the followingsequence. Give the sequence of values returned by the popoperations when this sequence of operations is performed on aninitially empty stack:

E A S * Y * Q U E * * * S T * * * I O * N * * *

Solution:

S Y E U Q T S A O N I E

Page 35: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Pushing and popping

From [Sedgewick, Exercise 4.6]:

A letter means push and an asterisk means pop in the followingsequence. Give the sequence of values returned by the popoperations when this sequence of operations is performed on aninitially empty stack:

E A S * Y * Q U E * * * S T * * * I O * N * * *

Solution:

S Y E U Q T S A O N I E

Page 36: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Checking balancedness

Develop the idea for a program that reads in a sequence ofcharacters, and determines whether its parentheses, braces, andcurly braces are “balanced”.

For example

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

is balanced, while

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

is not.

Solution:

When you read an opening bracket-symbol, push it onto thestack, when you read a closing bracket-symbol, check whetherit’s the top-symbol, and pop it.

Page 37: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Checking balancedness

Develop the idea for a program that reads in a sequence ofcharacters, and determines whether its parentheses, braces, andcurly braces are “balanced”.

For example

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

is balanced, while

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

is not.

Solution:

When you read an opening bracket-symbol, push it onto thestack, when you read a closing bracket-symbol, check whetherit’s the top-symbol, and pop it.

Page 38: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Pushing and popping again

A letter means enqueue and an asterisk means dequeue in thesequence

E A S * Y * Q U E * * * S T * * * I O * N * * *

Give the sequence of values returned by the dequeue operationswhen this sequence of operations is performed on an initiallyempty queue.

Solution:

E A S Y Q U E S T I O N

Page 39: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

Pushing and popping again

A letter means enqueue and an asterisk means dequeue in thesequence

E A S * Y * Q U E * * * S T * * * I O * N * * *

Give the sequence of values returned by the dequeue operationswhen this sequence of operations is performed on an initiallyempty queue.

Solution:

E A S Y Q U E S T I O N

Page 40: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

A queue via two stacks

Can we implement a queue using two stacksin an efficient way ?!

Solution: the basic idea is − · − = +

1 Use two stacks, IN and OUT.

2 The queue is empty iff both stacks are empty.

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

4 front (): if OUT is not-empty, perform OUT.top(),otherwise pop everything from IN, push it to OUT, andthen perform OUT.top().

5 pop(): The same as with front , only replacing OUT.top()with OUT.pop().

Page 41: Week 6 Oliver Dynamic Data structures Simple Special Stackscs.swan.ac.uk/~csoliver/Algorithms201314/Slides/06-data-structures.pdf · Implementation via an array Using an array we

CS 270

Algorithms

Oliver

Kullmann

Dynamic

sets

Simple

implementa-

tion

Special

cases

Stacks

Implementation

Queues

Implementation

Tutorial

A queue via two stacks

Can we implement a queue using two stacksin an efficient way ?!

Solution: the basic idea is − · − = +

1 Use two stacks, IN and OUT.

2 The queue is empty iff both stacks are empty.

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

4 front (): if OUT is not-empty, perform OUT.top(),otherwise pop everything from IN, push it to OUT, andthen perform OUT.top().

5 pop(): The same as with front , only replacing OUT.top()with OUT.pop().