data structures and algorithmsmarianzsu/dsa_mi/lectures/lecture09.pdfdata structures and algorithms...

120
DATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet ¸-Marian Zsuzsanna Babe¸ s - Bolyai University Computer Science and Mathematics Faculty 2019 - 2020 Lect. PhD. Onet ¸-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Upload: others

Post on 14-Oct-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

DATA STRUCTURES AND ALGORITHMSLECTURE 9

Lect. PhD. Onet-Marian Zsuzsanna

Babes - Bolyai UniversityComputer Science and Mathematics Faculty

2019 - 2020

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 2: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

In Lecture 8...

Linked List on Array

Container

ADT Multimap

ADT Matrix

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 3: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Today

Sorted Containers

ADT List

ADT Stack

ADT Queue

ADT Priority Queue

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 4: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Containers

There are many different containers, based on differentproperties:

do the elements have to be unique?

do the elements have positions assigned?

can we access any element or just some specific ones?

do we have simple elements, or key-value pairs?

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 5: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Sorted Containers

There are problems when we need a container where the orderof the elements is not important (there are no positions).

Such containers are Bag, Set, Map and Multimap and wehave already discussed them.

But sometimes we also need the elements of these containersto be sorted ⇒ SortedBag, SortedSet, SortedMap andSortedMultimap

Since these containers do not have positions, the only way tosee that they are indeed sorted, is to traverse them with aniterator. If we print the content of a sorted container using aniterator, elements need to be printed in order. And since theiterator needs to be fast, this means that internally theelements have to be stored ordered.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 6: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Sorted Containers

The sorted container are very similar to their non-sorted pair,they have mainly the same operations (same interface).

There is just one difference between the interfaces: when wewant to implement a sorted container we want it to be flexibleregarding the sorting part: we want to be able to change theway in which the elements are ordered without changing theimplementation

This is why for comparison we use a relation: an abstract wayof comparing elements

This relation has to be passed to the container when it iscreated: this is why the constructor of any ordered containerhas as parameter the relation that is used to order theelements.

We have already talked about ADT SortedBag (in Lecture 7),you can see this part with the relation there.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 7: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Sorted Containers

ADT Map and Multimap contain key-value pairs. When wehave a SortedMap and a SortedMultimap, the elements aresorted based on the key, so the relation used for sorting is onedefined for the keys.

In case of a SortedMultimap, we do not sort based on thevalues, not even when the keys are equal.

You have talked about ADT SortedMultimap in Seminar 4.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 8: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Example

Consider the following problem: In bowling a game is made ofseveral rounds and in each round a player has two rolls andthe score for the round is the total number of pins knockedover. There are two special cases: a strike, when a playerknocks down all pins with the first roll (and there is no secondroll) when the score of the round will be 10 plus the numberof pins knocked down in the next round and the a spare,when a player knocks down all pins with the two rolls in theround, when the score of the round will be 10 plus the numberof pins knocked down in the next roll. Given the number ofpins knocked down during X rounds, compute the final scoreof a player.

What are the characteristics of the container used for storingthe number of knocked down pins?

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 9: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Example

We have simple elements (the number of knocked down pins)

Elements are not unique

The order of the elements is important (we have positions)

The only container where there are positions is ADT List

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 10: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List

A list can be seen as a sequence of elements, where there isan order of the elements, and each element has a positioninside the list.

In a list, the order of the elements is important (positions areimportant).

A List is a container which is either empty or

it has a unique first element

it has a unique last element

for every element (except for the last) there is a uniquesuccessor element

for every element (except for the first) there is a uniquepredecessor element

In a list, we have operations which work with positions (inserton a position, remove from a position, etc.)

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 11: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List - Positions

Position of an element can be seen in different ways:as the rank of the element in the list (first, second, third, etc.)

similarly to an array, the position of an element is actually itsindex

as a reference to the memory location where the element isstored.

for example a pointer to the memory location

For a general treatment, we can consider the position of anelement in an abstract manner, and we can consider thatpositions are of type TPosition

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 12: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List I

Domain of the ADT List:

L = {l |l is a list with elements of type TElem, each havinga unique position in l of type TPosition}In the following we will discuss the interface of a List, wherethe positions are integer numbers (TPosition is an integernumber).

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 13: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List II

init(l)

descr: creates a new, empty list

pre: true

post: l ∈ L, l is an empty list

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 14: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List III

getElement(l, p)

descr: returns the element from a given position

pre: l ∈ L, p is an integer number, p is a valid position

post: getElement ← e, e ∈ TElem, e = the element fromposition p from l

throws: exception if p is not valid

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 15: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List IV

position(l, e)

descr: returns the position of an element

pre: l ∈ L, e ∈ TElem

post:

position← p integer number

p =

{the first position of element e from l if e ∈ l

−1 otherwise

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 16: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List V

modify(l, p, e)

descr: replaces an element from a position with another andreturns the old value from the position

pre: l ∈ L, p is an integer number, e ∈ TElem, p is a validposition

post: l ′ ∈ L, the element from position p from l’ is e,modify ← the old value from p

throws: exception if p is not valid

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 17: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List VI

insertFirst(l, e)

descr: inserts a new element at the beginning of a list

pre: l ∈ L, e ∈ TElem

post: l ′ ∈ L, the element e was added at the beginning of l

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 18: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List VII

insertLast(l, e)

descr: inserts a new element at the end of a list

pre: l ∈ L, e ∈ TElem

post: l ′ ∈ L, the element e was added at the end of l

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 19: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List VIII

insertAt(l, p, e)

descr: inserts a new element at a given position

pre: l ∈ L, p an integer number, e ∈ TElem, p is a validposition

post: l ′ ∈ L, the element e was added in l at position p (thepositions of all elements after p was increased by one).

throws: exception if p is not valid

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 20: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List IX

remove(l, p)

descr: removes and returns an element from a given positionfrom a list

pre: l ∈ L, p an integer number, p is a valid position

post: remove ← e, e ∈ TElem, e is the element from positionp from l, l ′ ∈ L, l’ = l - e.

throws: exception if p is not valid

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 21: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List X

search(l, e)

descr: searches for an element in the list

pre: l ∈ L, e ∈ TElem

post:

search←

{true if e ∈ l

false otherwise

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 22: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List XI

isEmpty(l)

descr: checks if a list is empty

pre: l ∈ Lpost:

isEmpty ←

{true if l = ∅false otherwise

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 23: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List XII

size(l)

descr: returns the number of elements from a list

pre: l ∈ Lpost: size ← the number of elements from l

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 24: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List XIII

destroy(l)

descr: destroys a list

pre: l ∈ Lpost: l was destroyed

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 25: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List XIV

iterator(l, it)

descr: returns an iterator for a list

pre: l ∈ Lpost:it ∈ I, it is an iterator over l

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 26: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

TPosition - C++

In STL, TPosition is represented by an iterator.

For example - vector:

iterator insert(iterator position, const value type& val)iterator erase (iterator position);

For example - list:

iterator insert(iterator position, const value type& val)iterator erase (iterator position);

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 27: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

TPosition - Java

In Java, TPosition is represented by an index.

We can add and remove using index and we can accesselements using their index (but we have iterator as well for theList).

There are fewer operations in the interface of the List

For example:

void add(int index, E element)E get(int index)E remove(int index)

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 28: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT SortedList

We can define the ADT SortedList, in which the elements arememorized in a given order, based on a relation.

Elements still have positions, we can access elements byposition.

Differences in the interface:

init takes as parameter a relationonly one insert operation existsno modify operation

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 29: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT SortedList

We can define the ADT SortedList, in which the elements arememorized in a given order, based on a relation.

Elements still have positions, we can access elements byposition.

Differences in the interface:

init takes as parameter a relationonly one insert operation existsno modify operation

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 30: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT List - representation

If we want to implement the ADT List (or ADT SortedList)we can use the following data structures are representation:

a (dynamic) array - elements are kept in a contiguous memorylocation - we have direct access to any element

a linked list - elements are kept in nodes, we do not havedirect access to any element

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 31: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Stack

Stack of books

Source: www.clipartfest.com

The word stack might be familiar from expressions like: stackof books, stack of paper or from the call stack that youusually see in debug windows.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 32: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Stack II

The ADT Stack represents a container in which access to theelements is restricted to one end of the container, called thetop of the stack.

When a new element is added, it will automatically be addedat the top.When an element is removed it will be removed automaticallyfrom the top.Only the element from the top can be accessed.

Because of this restricted access, the stack is said to have aLIFO policy: Last In, First Out (the last element that wasadded will be the first element that will be removed).

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 33: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Stack Example

Suppose that wehave the followingstack (green arrowshows the top ofthe stack):

We push thenumber 33:

We pop anelement:

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 34: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Stack Example II

This is our stack: We pop anotherelement:

We push thenumber 72:

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 35: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Stack Interface I

The domain of the ADT Stack:S = {s|s is a stack with elements of type TElem}

The interface of the ADT Stack contains the followingoperations:

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 36: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Stack Interface II

init(s)

Description: creates a new empty stack

Pre: True

Post: s ∈ S, s is an empty stack

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 37: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Stack Interface III

destroy(s)

Description: destroys a stack

Pre: s ∈ SPost: s was destroyed

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 38: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Stack Interface IV

push(s, e)

Description: pushes (adds) a new element onto the stack

Pre: s ∈ S, e is a TElem

Post: s ′ ∈ S, s ′ = s ⊕ e, e is the most recent element addedto the stack

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 39: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Stack Interface V

pop(s)

Description: pops (removes) the most recent element fromthe stack

Pre: s ∈ S, s is not empty

Post: pop ← e, e is a TElem, e is the most recent elementfrom s, s ′ ∈ S, s ′ = s e

Throws: an underflow error if the stack is empty

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 40: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Stack Interface VI

top(s)

Description: returns the most recent element from the stack(but it does not change the stack)

Pre: s ∈ S, s is not empty

Post: top ← e, e is a TElem, e is the most recent elementfrom s

Throws: an underflow error if the stack is empty

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 41: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Stack Interface VII

isEmpty(s)

Description: checks if the stack is empty (has no elements)

Pre: s ∈ SPost:

isEmpty ←{

true, if s has no elementsfalse, otherwise

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 42: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Stack Interface VIII

Note: stacks cannot be iterated, so they don’t have aniterator operation!

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 43: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Fixed-capacity Stack

If we know the maximum number of elements that we want tostore in the Stack, we have use a fixed-capacity Stack.

If we have a fixed capacity Stack, the constructor (initoperation) takes as parameter the capacity of the Stack (apositive integer number)

The push operation throws an exception if the stack is full

We can add an isFull operation as well (similar to the isEmptyoperation)

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 44: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Representation for Stack

Data structures that can be used to implement a stack:

Dynamic Array

Linked Lists (with dynamic allocation or on array)

Singly-Linked ListDoubly-Linked List

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 45: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Dynamic Array-based representation

? Where should we place the top of the stack for optimal perfor-mance?

We have two options:

Place top at the beginning of the array - every push and popoperation needs to shift every element to the right or left.

Place top at the end of the array - push and pop elementswithout moving the other ones.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 46: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Dynamic Array-based representation

? Where should we place the top of the stack for optimal perfor-mance?

We have two options:

Place top at the beginning of the array - every push and popoperation needs to shift every element to the right or left.

Place top at the end of the array - push and pop elementswithout moving the other ones.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 47: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Singly-Linked List-based representation

?Where should we place the top of the stack for optimal perfor-mance?

We have two options:

Place it at the end of the list (like we did when we used anarray) - for every push, pop and top operation we have toiterate through every element to get to the end of the list.

Place it at the beginning of the list - we can push and popelements without iterating through the list.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 48: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Singly-Linked List-based representation

?Where should we place the top of the stack for optimal perfor-mance?

We have two options:

Place it at the end of the list (like we did when we used anarray) - for every push, pop and top operation we have toiterate through every element to get to the end of the list.

Place it at the beginning of the list - we can push and popelements without iterating through the list.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 49: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Fixed capacity stack with singly-linked list

? How could we implement a stack with a fixed maximum capacityusing a singly-linked list?

We can keep in the Stack structure two integer values:maximum capacity and current size.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 50: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Fixed capacity stack with singly-linked list

? How could we implement a stack with a fixed maximum capacityusing a singly-linked list?

We can keep in the Stack structure two integer values:maximum capacity and current size.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 51: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Doubly-Linked List-based representation

?Where should we place the top of the stack for optimal perfor-mance?

We have two options:

Place it at the end of the list

Place it at the beginning of the list

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 52: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Doubly-Linked List-based representation

?Where should we place the top of the stack for optimal perfor-mance?

We have two options:

Place it at the end of the list

Place it at the beginning of the list

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 53: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

GetMinimum in constant time

? How can we design a special stack that has a getMinimum op-eration with Θ(1) time complexity (and the other operations haveΘ(1) time complexity as well)?

We can keep an auxiliary stack, containing as many elementsas the original stack, but containing the minimum value up toeach element. Let’s call this auxiliary stack a min stack andthe original stack the element stack.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 54: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

GetMinimum in constant time

? How can we design a special stack that has a getMinimum op-eration with Θ(1) time complexity (and the other operations haveΘ(1) time complexity as well)?

We can keep an auxiliary stack, containing as many elementsas the original stack, but containing the minimum value up toeach element. Let’s call this auxiliary stack a min stack andthe original stack the element stack.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 55: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

GetMinimum in constant time - Example

If this is the element stack: This is the corresponding minstack:

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 56: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

GetMinimum in constant time - Example

When a new element is pushed to the element stack, we pusha new element to the min stack as well. This element is theminimum between the top of the min stack and the newlyadded element.

The element stack: The corresponding min stack:

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 57: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

GetMinimum in constant time

When an element si popped from the element stack, we willpop an element from the min stack as well.

The getMinimum operation will simply return the top of themin stack.

The other stack operations remain unchanged (except init,where you have to create two stacks).

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 58: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

GetMinimum in constant time

Let’s implement the push operation for this SpecialStack,represented in the following way:

SpecialStack:elementStack: StackminStack: Stack

We will use an existing implementation for the stack and workonly with the operations from the interface.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 59: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Push for SpecialStack

subalgorithm push(ss, e) is:if isFull(ss.elementStack) then

@throw overflow (full stack) exceptionend-ifif isEmpty(ss.elementStack) then//the stacks are empty, just push the elem

push(ss.elementStack, e)push(ss.minStack, e)

elsepush(ss.elementStack, e)currentMin ← top(ss.minStack)if currentMin < e then //find the minim to push to minStack

push(ss.minStack, currentMin)else

push(ss.minStack, e)end-if

end-ifend-subalgorithm //Complexity: Θ(1)

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 60: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

SpecialStack - Notes / Think about it

We designed the special stack in such a way that all theoperations have a Θ(1) time complexity.

The disadvantage is that we occupy twice as much space aswith the regular stack.

? Think about how can we reduce the space occupied by the minstack to O(n) (especially if the minimum element of the stack rarelychanges). Hint: If the minimum does not change, we don’t haveto push a new element to the min stack. How can we implementthe push and pop operations in this case? What happens if theminimum element appears more than once in the element stack?

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 61: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Delimiter matching

Given a sequence of round brackets (parentheses), (square)brackets and curly brackets, verify if the brackets are openedand closed correctly.

For example:

The sequence ()([][][(())]) - is correctThe sequence [()()()()] - is correctThe sequence [()]) - is not correct (one extra closed roundbracket at the end)The sequence [(]) - is not correct (brackets closed in wrongorder)The sequence {[[]] () - is not correct (curly bracket is notclosed)

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 62: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Bracket matching - Solution Idea

Stacks are suitable for this problem, because the bracket thatwas opened last should be the first to be closed. This matchesthe LIFO property of the stack.

The main idea of the solution:

Start parsing the sequence, element-by-elementIf we encounter an open bracket, we push it to a stackIf we encounter a closed bracket, we pop the last open bracketfrom the stack and check if they matchIf they don’t match, the sequence is not correctIf they match, we continueIf the stack is empty when we finished parsing the sequence, itwas correct

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 63: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Bracket matching - Extension

How can we extend the previous idea so that in case of anerror we will also signal the position where the problemoccurs?

Remember, we have 3 types of errors:

Open brackets that are never closed

Closed brackets that were not opened

Mismatch

Keep count of the current position in the sequence, and pushto the stack < delimiter , position > pairs.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 64: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Bracket matching - Extension

How can we extend the previous idea so that in case of anerror we will also signal the position where the problemoccurs?

Remember, we have 3 types of errors:

Open brackets that are never closed

Closed brackets that were not opened

Mismatch

Keep count of the current position in the sequence, and pushto the stack < delimiter , position > pairs.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 65: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Queue

The ADT Queue represents a container in which access to theelements is restricted to the two ends of the container, calledfront and rear.

When a new element is added (pushed), it has to be added tothe rear of the queue.

When an element is removed (popped), it will be the one atthe front of the queue.

Because of this restricted access, the queue is said to have aFIFO policy: First In First Out.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 66: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Queue - Example

Assume that wehave this queue(green arrow is thefront, red arrow isthe rear)

Push number 33: Pop an element:

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 67: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Queue - Example

This is our queue: Pop an element: Push number 72:

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 68: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Queue - Interface I

The domain of the ADT Queue:Q = {q|q is a queue with elements of type TElem}

The interface of the ADT Queue contains the followingoperations:

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 69: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Queue - Interface II

init(q)

Description: creates a new empty queue

Pre: True

Post: q ∈ Q, q is an empty queue

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 70: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Queue - Interface III

destroy(q)

Description: destroys a queue

Pre: q ∈ QPost: q was destroyed

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 71: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Queue - Interface IV

push(q, e)

Description: pushes (adds) a new element to the rear of thequeue

Pre: q ∈ Q, e is a TElem

Post: q′ ∈ Q, q′ = q ⊕ e, e is the element at the rear of thequeue

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 72: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Queue - Interface V

pop(q)

Description: pops (removes) the element from the front ofthe queue

Pre: q ∈ Q, q is not empty

Post: pop ← e, e is a TElem, e is the element at the front ofq, q′ ∈ Q, q′ = q e

Throws: an underflow error if the queue is empty

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 73: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Queue - Interface VI

top(q)

Description: returns the element from the front of the queue(but it does not change the queue)

Pre: q ∈ Q, qis not empty

Post: top ← e, e is a TElem, e is the element from the frontof q

Throws: an underflow error if the queue is empty

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 74: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Queue - Interface VII

isEmpty(s)

Description: checks if the queue is empty (has no elements)

Pre: q ∈ QPost:

isEmpty ←{

true, if q has no elementsfalse, otherwise

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 75: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Queue - Interface VIII

Note: queues cannot be iterated, so they don’t have aniterator operation!

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 76: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Queue - Representation

What data structures can be used to implement a Queue?

Dynamic Array

Singly Linked List

Doubly Linked List

For each possible representation we will discuss where weshould place the front and the rear of the queue and thecomplexity of the operations.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 77: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Queue - Array-based representation

If we want to implement a Queue using an array, where shouldwe place the front and the rear of the queue?

In theory, we have two options:

Put front at the beginning of the array and rear at the end

Put front at the end of the array and rear at the beginning

In either case we will have one operation (push or pop) thatwill have Θ(n) complexity.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 78: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Queue - Array-based representation

If we want to implement a Queue using an array, where shouldwe place the front and the rear of the queue?

In theory, we have two options:

Put front at the beginning of the array and rear at the end

Put front at the end of the array and rear at the beginning

In either case we will have one operation (push or pop) thatwill have Θ(n) complexity.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 79: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Queue - Array-based representation

We can improve the complexity of the operations, if we do notinsist on having either front or rear at the beginning of thearray (at position 1).

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 80: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Queue - Array-based representation

This is our queue(green arrow is thefront, red arrow isthe rear)

Push number 33: Pop an element(and do not movethe otherelements):

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 81: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Queue - Array-based representation

Pop anotherelement:

Push number 11: Pop an element:

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 82: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Queue - Array-based representation

Push number 86: Push number 19:

This is called a circular array.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 83: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Queue - representation on a SLL

If we want to implement a Queue using a singly linked list,where should we place the front and the rear of the queue?

In theory, we have two options:

Put front at the beginning of the list and rear at the end

Put front at the end of the list and rear at the beginning

In either case we will have one operation (push or pop) thatwill have Θ(n) complexity.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 84: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Queue - representation on a SLL

If we want to implement a Queue using a singly linked list,where should we place the front and the rear of the queue?

In theory, we have two options:

Put front at the beginning of the list and rear at the end

Put front at the end of the list and rear at the beginning

In either case we will have one operation (push or pop) thatwill have Θ(n) complexity.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 85: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Queue - representation on a SLL

We can improve the complexity of the operations if, eventhough the list is singly linked, we keep both the head and thetail of the list.

What should the tail of the list be: the front or the rear ofthe queue?

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 86: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Queue - representation on a DLL

If we want to implement a Queue using a doubly linked list,where should we place the front and the rear of the queue?

In theory, we have two options:

Put front at the beginning of the list and rear at the end

Put front at the end of the list and rear at the beginning

In either case we will have both operations (push or pop) inΘ(1) complexity.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 87: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Queue - representation on a DLL

If we want to implement a Queue using a doubly linked list,where should we place the front and the rear of the queue?

In theory, we have two options:

Put front at the beginning of the list and rear at the end

Put front at the end of the list and rear at the beginning

In either case we will have both operations (push or pop) inΘ(1) complexity.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 88: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Evaluating an arithmetic expression

We want to write an algorithm that can compute the result ofan arithmetic expression:

For example:

2+3*4 = 14((2+4)*7)+3*(9-5) = 54((((3+1)*3)/((9-5)+2))-((3*(7-4)) + 6)) = -13

An arithmetic expression is composed of operators (+, -, * or/), parentheses and operands (the numbers we are workingwith). For simplicity we are going to use single digits asoperands and we suppose that the expression is correct.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 89: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Infix and postfix notations

The arithmetic expressions presented on the previous slide arein the so-called infix notation. This means that the operatorsare between the two operands that they refer to. Humansusually use this notation, but for a computer algorithm it iscomplicated to compute the result of an expression in an infixnotation.

Computers can work a lot easier with the postfix notation,where the operator comes after the operands.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 90: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Infix and postfix notations

Examples of expressions in infix notation and thecorresponding postfix notations:

Infix notation Postfix notation1+2 12+

1+2-3 12+3-

4*3+6 43*6+

4*(3+6) 436+*

(5+6)*(4-1) 56+41-*

1+2*(3-4/(5+6)) 123456+/-*+

The order of the operands is the same for both the infix andthe postfix notations, only the order of the operators changes

The operators have to be ordered taking into considerationoperator precedence and the parentheses

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 91: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Infix and postfix notations

So, evaluating an arithmetic expression is divided into twosubproblems:

Transform the infix notation into a postfix notation

Evaluate the postfix notation

Both subproblems are solved using stacks and queues.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 92: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Infix to postfix transformation - The main idea

Use an auxiliary stack for the operators and parentheses and aqueue for the result.

Start parsing the expression.

If an operand is found, push it to the queue

If an open parenthesis is found, it is pushed to the stack.

If a closed parenthesis is found, pop elements from the stackand push them to the queue until an open parenthesis isfound (but do not push parentheses to the queue).

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 93: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Infix to postfix transformation - The main idea

If an operator (opCurrent) is found:

If the stack is empty, push the operator to the stackWhile the top of the stack contains an operator with a higheror equal precedence than the current operator, pop and pushto the queue the operator from the stack. Push opCurrent tothe stack when the stack becomes empty, its top is aparenthesis or an operator with lower precedence.If the top of the stack is open parenthesis or operator withlower precedence, push opCurrent to the stack.

When the expression is completely parsed, pop everythingfrom the stack and push to the queue.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 94: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Infix to postfix transformation - Example

Let’s follow the transformation of 1+2*(3-4/(5+6))+7

Input Operation Stack Queue1 Push to Queue 1+ Push to stack + 12 Push to Queue + 12* Check (no Pop) and Push +* 12( Push to stack +*( 123 Push to Queue +*( 123- Check (no Pop) and Push +*(- 1234 Push to Queue +*(- 1234/ Check (no Pop) and Push +*(-/ 1234( Push to stack +*(-/( 12345 Push to Queue +*(-/( 12345+ Check (no Pop) and Push +*(-/(+ 123456 Push to Queue +*(-/(+ 123456) Pop and push to Queue till ( +*(-/ 123456+) Pop and push to Queue till ( +* 123456+/-+ Check, Pop twice and Push + 123456+/-*+7 Push to Queue + 123456+/-*+7

over Pop everything and push to Queue 123456+/-*+7+

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 95: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Infix to postfix transformation - Example

Let’s follow the transformation of 1+2*(3-4/(5+6))+7

Input Operation Stack Queue1 Push to Queue 1+ Push to stack + 12 Push to Queue + 12* Check (no Pop) and Push +* 12( Push to stack +*( 123 Push to Queue +*( 123- Check (no Pop) and Push +*(- 1234 Push to Queue +*(- 1234/ Check (no Pop) and Push +*(-/ 1234( Push to stack +*(-/( 12345 Push to Queue +*(-/( 12345+ Check (no Pop) and Push +*(-/(+ 123456 Push to Queue +*(-/(+ 123456) Pop and push to Queue till ( +*(-/ 123456+) Pop and push to Queue till ( +* 123456+/-+ Check, Pop twice and Push + 123456+/-*+7 Push to Queue + 123456+/-*+7

over Pop everything and push to Queue 123456+/-*+7+

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 96: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Evaluation of expression in postfix notation

Once we have the postfix notation we can compute the valueof the expression using a stack

The main idea of the algorithm:

Use an auxiliary stackStart parsing the expressionIf an operand if found, it is pushed to the stackIf an operator is found, two values are popped from the stack,the operation is performed and the result is pushed to the stackWhen the expression is parsed, the stack contains the result

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 97: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Evaluation of postfix notation - Example

Let’s follow the evaluation of 123456+/-*+7+

Pop from the queue Operation Stack1 Push 1

2 Push 1 2

3 Push 1 2 3

4 Push 1 2 3 4

5 Push 1 2 3 4 5

6 Push 1 2 3 4 5 6

+ Pop, add, Push 1 2 3 4 11

/ Pop, divide, Push 1 2 3 0

- Pop, subtract, Push 1 2 3

* Pop, multiply, Push 1 6

+ Pop, add, Push 7

7 Push 7 7

+ Pop, add, Push 14

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 98: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Evaluation of postfix notation - Example

Let’s follow the evaluation of 123456+/-*+7+

Pop from the queue Operation Stack1 Push 1

2 Push 1 2

3 Push 1 2 3

4 Push 1 2 3 4

5 Push 1 2 3 4 5

6 Push 1 2 3 4 5 6

+ Pop, add, Push 1 2 3 4 11

/ Pop, divide, Push 1 2 3 0

- Pop, subtract, Push 1 2 3

* Pop, multiply, Push 1 6

+ Pop, add, Push 7

7 Push 7 7

+ Pop, add, Push 14

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 99: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Evaluation of an arithmetic expression

Combining the two functions we can compute the result of anarithmetic expression.

How can we evaluate directly the expression in infix notationwith one single function? Hint: use two stacks.

How can we add exponentiation as a fifth operation?

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 100: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Priority Queue

The ADT Priority Queue is a container in which each elementhas an associated priority (of type TPriority).

In a Priority Queue access to the elements is restricted: wecan access only the element with the highest priority.

Because of this restricted access, we say that the PriorityQueue works based on a HPF - Highest Priority First policy.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 101: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

ADT Priority Queue

In order to work in a more general manner, we can define arelation R on the set of priorities: R : TPriority × TPriority

When we say the element with the highest priority we willmean that the highest priority is determined using this relationR.

If the relation R = ”≥”, the element with the highest priorityis the one for which the value of the priority is the largest(maximum).

Similarly, if the relation R = ”≤”, the element with thehighest priority is the one for which the value of the priority isthe lowest (minimum).

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 102: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Interface I

The domain of the ADT Priority Queue:PQ = {pq|pq is a priority queue with elements (e, p), e ∈TElem, p ∈ TPriority}

The interface of the ADT Priority Queue contains thefollowing operations:

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 103: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Interface II

init (pq, R)

Description: creates a new empty priority queue

Pre: R is a relation over the priorities,R : TPriority × TPriority

Post: pq ∈ PQ, pq is an empty priority queue

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 104: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Interface III

destroy(pq)

Description: destroys a priority queue

Pre: pq ∈ PQPost: pq was destroyed

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 105: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Interface IV

push(pq, e, p)

Description: pushes (adds) a new element to the priorityqueue

Pre: pq ∈ PQ, e ∈ TElem, p ∈ TPriority

Post: pq′ ∈ PQ, pq′ = pq ⊕ (e, p)

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 106: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Interface V

pop (pq, e, p)

Description: pops (removes) from the priority queue theelement with the highest priority. It returns both the elementand its priority

Pre: pq ∈ PQ, pq is not empty

Post:e ∈ TElem, p ∈ TPriority , e is the element with thehighest priority from pq, p is its priority.pq′ ∈ PQ, pq′ = pq (e, p)

Throws: an exception if the priority queue is empty.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 107: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Interface VI

top (pq, e, p)

Description: returns from the priority queue the element withthe highest priority and its priority. It does not modify thepriority queue.

Pre: pq ∈ PQ, pq is not empty

Post: e ∈ TElem, p ∈ TPriority , e is the element with thehighest priority from pq, p is its priority.

Throws: an exception if the priority queue is empty.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 108: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Interface VII

isEmpty(pq)

Description: checks if the priority queue is empty (it has noelements)

Pre: pq ∈ PQPost:

isEmpty ←{

true, if pq has no elementsfalse, otherwise

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 109: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Interface VIII

Note: priority queues cannot be iterated, so they don’t havean iterator operation!

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 110: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Representation

What data structures can be used to implement a priorityqueue?

Dynamic Array

Linked List

(Binary) Heap

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 111: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Representation

If the representation is a Dynamic Array or a Linked List wehave to decide how we store the elements in the array/list:

we can keep the elements ordered by their priorities

we can keep the elements in the order in which they wereinserted

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 112: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Representation

Complexity of the main operations for the two representationoptions:

Operation Sorted Non-sortedpush O(n) Θ(1)

pop Θ(1) Θ(n)

top Θ(1) Θ(n)

What happens if we keep in a separate field the element withthe highest priority?

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 113: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Representation

Another representation for a Priority Queue is to use a binaryheap, where the root of the heap is the element with thehighest priority (the figure contains the priorities only).

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 114: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Representation

The previous array, interpreted as a binary heap:

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 115: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Representation on a binary heap

When an element is pushed to the priority queue, it is simplyadded to the heap (and bubbled-up if needed)

When an element is popped from the priority queue, the rootis removed from the heap (and bubble-down is performed ifneeded)

Top simply returns the root of the heap.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 116: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Priority Queue - Representation

Let’s complete our table with the complexity of the operationsif we use a heap as representation:

Operation Sorted Non-sorted Heappush O(n) Θ(1) O(log2n)

pop Θ(1) Θ(n) O(log2n)

top Θ(1) Θ(n) Θ(1)

Consider the total complexity of the following sequence ofoperations:

start with an empty priority queuepush n random elements to the priority queueperform pop n times

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 117: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Think about it - Linked Lists

Write a non-recursive algorithm to reverse a singly linked listwith Θ(n) time complexity, using constant space/memory.

Suppose there are two singly linked lists both of whichintersect at some point and become a single linked list (seethe image below). The number of nodes in the two listsbefore the intersection is not known and may be different ineach list. Give an algorithm for finding the merging point(hint - use a Stack)

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 118: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Think about it - Stacks and Queues I

How can we implement a Stack using two Queues? What willbe the complexity of the operations?

How can we implement a Queue using two Stacks? What willbe the complexity of the operations?

How can we implement two Stacks using only one array? Thestack operations should throw an exception only if the totalnumber of elements in the two Stacks is equal to the size ofthe array.

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 119: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Think about it - Stacks and Queues II

Given a string of lower-case characters, recursively removeadjacent duplicate characters from the string. For example,for the word ”mississippi” the result should be ”m”.

Given an integer k and a queue of integer numbers, how canwe reverse the order of the first k elements from the queue?For example, if k=4 and the queue has the elements [10, 20,30, 40, 50, 60, 70, 80, 90], the output should be [40, 30, 20,10, 50, 60, 70, 80, 90].

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS

Page 120: DATA STRUCTURES AND ALGORITHMSmarianzsu/DSA_MI/Lectures/Lecture09.pdfDATA STRUCTURES AND ALGORITHMS LECTURE 9 Lect. PhD. Onet˘-Marian Zsuzsanna Babe˘s - Bolyai University Computer

Think about it - Priority Queues

How can we implement a stack using a Priority Queue?

How can we implement a queue using a Priority Queue?

Lect. PhD. Onet-Marian Zsuzsanna DATA STRUCTURES AND ALGORITHMS