Foundations of Data Structures

Similar documents
Data Structures Lecture 5

Outline and Reading. The Stack ADT ( 2.1.1) Applications of Stacks ( 2.1.1) Array-based implementation ( 2.1.1) Growable array-based stack ( 1.

Stacks Goodrich, Tamassia

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004)

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )

Stacks Goodrich, Tamassia Stacks

HOWDY! WELCOME TO CSCE 221 DATA STRUCTURES AND ALGORITHMS

1/18/12. Chapter 5: Stacks, Queues and Deques. Stacks. Outline and Reading. Nancy Amato Parasol Lab, Dept. CSE, Texas A&M University

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified.

Lecture 3 Linear Data Structures: Arrays, Array Lists, Stacks, Queues and Linked Lists

Queues COL 106. Slides by Amit Kumar, Shweta Agrawal

Outline and Reading. The Stack ADT ( 4.2.1) Applications of Stacks ( 4.2.3) Array-based implementation ( 4.2.2) Growable array-based stack.

Stacks. Lecture6: Stacks. Stack Operations. Stack Interface in Java

Stacks Goodrich, Tamassia, Goldwasser Stacks

COMP9024: Data Structures and Algorithms

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S

Lecture 3 Linear Data Structures

Lecture 3 Linear Data Structures

csci 210: Data Structures Stacks and Queues

Ch02 Data Structures

Ch02 Data Structures

This lecture. Abstract Data Types (ADTs) The Stack ADT ( 4.2) Stacks. Stack Interface in Java. Exceptions. Abstract data types Stacks Queues

Elementary Data Structures. Stacks, Queues, & Lists Amortized analysis Trees

IT 4043 Data Structures and Algorithms. Budditha Hettige Department of Computer Science

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

PA3 Design Specification

data structures and algorithms lecture 6

DataStruct 5. Stacks, Queues, and Deques

Stacks. Revised based on textbook author s notes.

How many times is the loop executed? middle = (left+right)/2; if (value == arr[middle]) return true;

STACKS AND QUEUES. Problem Solving with Computers-II

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

CSE Data Structures and Algorithms... In Java! Stacks. CSE2100 DS & Algorithms 1

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

The Stack and Queue Types

COSC160: Data Structures: Lists and Queues. Jeremy Bolton, PhD Assistant Teaching Professor

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1

CSC148H Week 3. Sadia Sharmin. May 24, /20

CSE 143. Lecture 4: Stacks and Queues

Lecture 3 Linear Data Structures

12 Abstract Data Types

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle.

Lecture 4 Stack and Queue

Motivation for Queues

CSC148 Week 2. Larry Zhang

Data Structure - Stack and Queue-

March 13/2003 Jayakanth Srinivasan,

CSCI 204 Introduction to Computer Science II. Lab 6: Stack ADT

LIFO : Last In First Out

Building Java Programs


15. Stacks and Queues

Lecture Data Structure Stack

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Data Structures, Algorithms & Data Science Platforms

Stack Abstract Data Type

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Queues Fall 2018 Margaret Reid-Miller

CPSC 221: Algorithms and Data Structures ADTs, Stacks, and Queues

1 P age DS & OOPS / UNIT II

CPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues

CS 206 Introduction to Computer Science II

Lists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Postfix (and prefix) notation

Linear Data Structures

Information Science 2

infix expressions (review)

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Programming, Data Structures and Algorithms Prof. Hema A Murthy Department of Computer Science and Engineering Indian Institute of Technology, Madras

Lecture 12 ADTs and Stacks

-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed "stack method of expression evaluation" in 1955.

Your Topic Goes Here Queue

E.G.S. PILLAY ENGINEERING COLLEGE (An Autonomous Institution, Affiliated to Anna University, Chennai) Nagore Post, Nagapattinam , Tamilnadu.

.:: UNIT 4 ::. STACK AND QUEUE

Ch. 18: ADTs: Stacks and Queues. Abstract Data Type

Lecture 3: Stacks & Queues

CS200: Queues. Prichard Ch. 8. CS200 - Queues 1

DATA STRUCTURE UNIT I

DATA STRUCTURES AND ALGORITHMS

Data Abstraction and Specification of ADTs

Where does the insert method place the new entry in the array? Assume array indexing starts from 0(zero).

Stack Applications. Lecture 27 Sections Robb T. Koether. Hampden-Sydney College. Wed, Mar 29, 2017

CS 206 Introduction to Computer Science II

CS W3134: Data Structures in Java

Algorithms and Data Structures

Stacks Fall 2018 Margaret Reid-Miller

DATA STRUCUTRES. A data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

CMSC Introduction to Algorithms Spring 2012 Lecture 7

CSE 214 Computer Science II Stack

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures

Stacks, Queues (cont d)

Data structure and algorithm in Python

DEEPIKA KAMBOJ UNIT 2. What is Stack?

Apply to be a Meiklejohn! tinyurl.com/meikapply

! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples:

Transcription:

Foundations of Data Structures Lecture 4 Elementary Abstract Data Types (ADT): Stack Queue 1

Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations on the data Error conditions associated with operations 2

Linear Structures A structure is linearif it has these 2 properties: (P1) Each element is `followed by' at most one other element (P2) No two elements are `followed by' the same element An array is a linear structure. A->B->C->D Counter example 1 (violates P1): B<-A->C Counter example 2 (violates P2): A->C<-B 3

Stacks Linear structure. One end is called top. Other end is called bottom. Additions to and removals from the topend only. 4

Stack Of Cups top E top F E D D C C B B bottom A bottom A Add a cup to the stack. Remove a cup from new stack. A stack is a LIFO list. 5

Stack Specification A stack is either emptyor it consists of two parts: a top element a stack (the remaining elements). The elements in a stack may be of any type, but all the elements in a given stack must be the same type. 6

The Stack ADT: Data Stored The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in firstout scheme Think of a spring-loaded plate dispenser 7

The Stack ADT: Operations Main stack operations: push(object): inserts an element object pop(): removes and returns the last inserted element Auxiliary stack operations: object top(): returns the last inserted element without removing it makeemptystack(): initialize an empty stack integer size(): returns the number of elements stored booleanisemptystack(): indicates whether no elements are stored 8

The Stack ADT: Exceptions Attempting the execution of an operation of ADT may sometimes cause an error condition, called an exception Exceptions are said to be thrown by an operation that cannot be executed In the Stack ADT, operations pop and top cannot be performed if the stack is empty Attempting the execution of pop or top on an empty stack throws an EmptyStackException 9

Applications of Stacks Direct applications Page-visited history in a Web browser Undo sequence in a text editor Chain of method calls in the Java Virtual Machine Indirect applications Auxiliary data structure for algorithms Component of other data structures 10

Array-based Stack A simple way of implementing the Stack ADT uses an array We add elements from left to right A variable keeps track of the index of the top element Algorithm size() return t + 1 Algorithm pop() if isempty() then throw EmptyStackException else t t 1 return S[t + 1] 11

Array-based Stack (cont.) The array storing the stack elements may become full A push operation will then throw a FullStackException Limitation of the array based implementation Not intrinsic to the Stack ADT Algorithm push(o) ift =S.length 1 then throw FullStackException else t t + 1 S[t] o 12

Performance and Limitations Performance Let n be the number of elements in the stack The space used is O(n) Each operation runs in time O(1) Limitations The maximum size of the stack must be defined a priori and cannot be changed Trying to push a new element into a full stack causes an implementation-specific exception 13

Computing Spans We show how to use a stack as an auxiliary data structure in an algorithm Given an an array X, the span S[i] ofx[i] is the maximum number of consecutive elements X[j] immediatelypreceding X[i] and such that X[j] X[i] Spans have applications to financial analysis 14

Quadratic Algorithm Algorithm spans1(x, n) Input arrayx ofn integers Output arrays of spans of X # S new array of n integers n fori 0ton 1do n s 1 n while s i X[i s] X[i] do 1 + 2 + +(n 1) s s + 1 1 + 2 + +(n 1) S[i] s n return S 1 Algorithm spans1runs in O(n 2 ) time 15

Computing Spans with a Stack We keep in a stack the indices of the elements visible when looking back We scan the array from left to right Let i be the current index We pop indices from the stack until we find index jsuch that X[i]< X[j] We set S[i] i j We push ionto the stack 7 6 5 4 3 2 1 0 0 1 2 3 4 5 6 7 16

Linear Algorithm Each index of the array Is pushed into the stack exactly one Is popped from the stack at most once The statements in the while-loop are executed at most n times Algorithm spans2 runs in O(n) time Algorithm spans2(x, n) # S new array of n integers n A new empty stack 1 for i 0to n 1do n while ( A.isEmpty() X[top()] X[i] ) do n A.pop() n if A.isEmpty() then n S[i] i+1 n else S[i] i top() n A.push(i) n return S 1 Stacks 17

Parentheses Matching Each (, {, or [ must be paired with a matching ), }, or [ correct: ( )(( )){([( )])} correct: ((( )(( )){([( )])})) incorrect: )(( )){([( )])} incorrect: ({[ ])} incorrect: ( 18

Parentheses Matching Algorithm Algorithm ParenMatch(X,n) Input: An array X of n tokens, each of which is either a grouping symbol, a variable, an arithmetic operator, or a number Output: true if and only if all the grouping symbols in X match A new empty stack for i 0to n - 1 do if X[i] is an opening grouping symbol then S.push(X[i]) else if X[i] is a closing grouping symbol then if S.isEmpty() then return false {nothing to match with} if S.pop() does not match the type of X[i] then return false {wrong type} if S.isEmpty() then return true {every symbol matched} else return false {some symbols were never matched} 19

Example (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n) 20

Infix to Postfix Conversion Rules: Operands immediately go directly to output Operators are pushed into the stack (including parenthesis) - Check to see if stack top operator is less than current operator - If the top operator is less than, push the current operator onto stack - If the top operator is greater than the current, pop top operator and print, push current operator onto stack - Priority 2: * / - Priority 1: + - - Priority 0: ( If we encounter a right parenthesis, pop from stack until we get matching left parenthesis. Do not output parenthesis.

Infix to Postfix Example A + B * C - D / E Infix Stack(bot->top) Postfix a) A + B * C - D / E b) + B * C - D / E A c) B * C - D / E + A d) * C - D / E + A B e) C - D / E + * A B f) - D / E + * A B C g) D / E + - A B C * h) / E + - A B C * D i) E + - / A B C * D j) + - / A B C * D E k) A B C * D E / - +

Infix to Postfix Example #2 A * B - ( C + D ) + E Infix Stack(bot->top) Postfix a) A * B - ( C + D ) + E empty empty b) * B - ( C + D ) + E empty A c) B - ( C + D ) + E * A d) - ( C + D ) + E * A B e) - ( C + D ) + E empty A B * f) ( C + D ) + E - A B * g) C + D ) + E - ( A B * h) + D ) + E - ( A B * C i) D ) + E - ( + A B * C j) ) + E - ( + A B * C D k) + E - A B * C D + l) + E empty A B * C D + - m) E + A B * C D + - n) + A B * C D + - E o) empty A B * C D + - E +

Postfix Evaluation Operand: push Operator: pop 2 operands, do the math, pop result back onto stack 1 2 3 + * Postfix Stack( bot -> top ) a) 1 2 3 + * b) 2 3 + * 1 c) 3 + * 1 2 d) + * 1 2 3 e) * 1 5 // 5 from 2 + 3 f) 5 // 5 from 1 * 5

Rat In A Maze 25

Rat In A Maze Move order is: right,down,left, up Block positions to avoid revisit. 26

Rat In A Maze Move order is: right, down, left, up Block positions to avoid revisit. 27

Rat In A Maze Move backward until we reach a square from which a forward move is possible. 28

Rat In A Maze Move down. 29

Rat In A Maze Move left. 30

Rat In A Maze Move down. 31

Rat In A Maze Move backward until we reach a square from which a forward move is possible. 32

Rat In A Maze Move backward until we reach a square from which a forward move is possible. 33 Move downward.

Rat In A Maze Move right. Backtrack. 34

Rat In A Maze Move downward. 35

Rat In A Maze Move right. 36

Rat In A Maze Move one down and then right. 37

Rat In A Maze Move one up and then right. 38

Rat In A Maze Move down to exit and eat cheese. Path from maze entry to current position operates as a stack. 39

Rat In A Maze 40

Queue Linear list. One end is called front. Other end is called rear. Additions are done at the rearonly. Removals are made from the front only. 41

The Queue ADT: Data Stored The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in first-out scheme (FIFO) Insertions are at the rear of the queue and removals are at the front of the queue 42

The Queue ADT: Operations Main queue operations: enqueue(object): inserts an element at the end of the queue object dequeue(): removes and returns the element at the front of the queue Auxiliary queue operations: object front(): returns the element at the front without removing it integer size(): returns the number of elements stored booleanisemptyqueue(): indicates whether no elements are stored createemptyqueue(): initialize an empty queue 43

The Queue ADT: Exceptions Attempting the execution of dequeue or front on an empty queue throws an EmptyQueueException 44

Queue Example Operation Output Q enqueue(5) (5) enqueue(3) (5, 3) dequeue() 5 (3) enqueue(7) (3, 7) dequeue() 3 (7) front() 7 (7) dequeue() 7 () dequeue() error () isempty() true () enqueue(9) (9) enqueue(7) (9, 7) size() 2 (9, 7) enqueue(3) (9, 7, 3) enqueue(5) (9, 7, 3, 5) dequeue() 9 (7, 3, 5) Queues 45

Array-based Queue Use an array of size Nin a circular fashion Two variables keep track of the front and rear f index of the front element r index immediately past the rear element Array location r is kept empty normal configuration Q 0 1 2 f r wrapped-around configuration Q 0 1 2 r f Queues 46

Queue Operations We use the modulo operator (remainder of division) Algorithm size() return (N f+ r) mod N Q Q 0 1 2 f r 0 1 2 r f Queues 47

Queue Operations (cont.) Operation enqueue throws an exception if the array is full This exception is implementationdependent Algorithm enqueue(o) if size() = N 1then throw FullQueueException else Q[r] o r (r + 1) mod N Q Q 0 1 2 f r 0 1 2 r f Queues 48

Queue Operations (cont.) Operation dequeue throws an exception if the queue is empty This exception is specified in the queue ADT Algorithm dequeue() if isempty() then throw EmptyQueueException else o Q[f] f (f + 1) mod N return o Q Q 0 1 2 f r 0 1 2 r f Queues 49

Performance and Limitations Performance Let n be the number of elements in the queue The space used is O(n) Each operation runs in time O(1) Limitations Trying to enqueuea new element into a full queue or dequeuefrom an empty queue causes an implementation-specific exception 50

Applications of Queues Direct applications Waiting lists, bureaucracy Access to shared resources (e.g., printer) Multiprogramming Indirect applications Auxiliary data structure for algorithms Component of other data structures Queues 51

Lee s Wire Router start pin end pin Label all reachable squares 1 unit from start.

Lee s Wire Router start pin end pin 1 1 Label all reachable unlabeled squares 2 units from start.

Lee s Wire Router start pin end pin 2 1 2 2 1 2 2 Label all reachable unlabeled squares 3 units from start.

Lee s Wire Router start pin end pin 3 2 1 2 3 3 2 1 2 3 2 Label all reachable unlabeled squares 4 units from start.

Lee s Wire Router start pin end pin 3 2 1 2 3 4 4 4 3 2 1 2 3 4 2 4 Label all reachable unlabeled squares 5 units from start.

Lee s Wire Router start pin end pin 5 4 5 3 3 2 2 1 1 2 2 2 3 4 3 4 4 5 4 5 5 5 Label all reachable unlabeled squares 6 units from start.

Lee s Wire Router start pin end pin 6 5 6 4 5 3 3 2 2 1 1 2 2 2 3 4 3 4 4 4 5 6 5 5 6 6 6 5 6 6 End pin reached. Traceback.

Lee s Wire Router start pin end pin 6 5 6 4 5 3 3 2 2 1 1 2 2 2 6 3 4 3 4 5 6 4 4 5 5 5 6 6 6 6 End pin reached. Traceback.