Stacks Stacks.

Slides:



Advertisements
Similar presentations
Stacks.
Advertisements

Chapter 5.
Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be instantiated.
CS Data Structures ( 資料結構 ) Chapter 3: Stacks and Queues Spring 2012.
Stacks. Queues. Double-Ended Queues. 2 CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 © 2010 Goodrich, Tamassia.
Stacks. 2 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.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 The Stack ADT (§4.2) The Stack ADT stores arbitrary objects Insertions and deletions.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Applications of Stacks Direct applications Delimiter matching Undo sequence in a text.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Topic 15 Implementing and Using Stacks
Introduction to Stacks What is a Stack Stack implementation using arrays. Application of Stack.
Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
Stacks. 2 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.5)
Implementing and Using Stacks
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Stacks. week 2a2 Outline and Reading The Stack ADT (§4.1) Applications of Stacks Array-based implementation (§4.1.2) Growable array-based stack Think.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
Stacks © 2010 Goodrich, Tamassia1Stacks. 2 Abstract Data Types (ADTs)  An abstract data type (ADT) is an abstraction of a data structure  An ADT specifies:
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
Stack. 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.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Stacks & Queues EECS: Stacks & Queues Stacks April 23, 2017
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
Lecture6: Stacks Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
Parasol Lab, Dept. CSE, Texas A&M University
Welcome to CSCE 221 – Data Structures and Algorithms
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
CH 5 : STACKS, QUEUES, AND DEQUES ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA.
Stack. ADS2 Lecture 1010 The Stack ADT (GoTa §5.1) The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2a. Simple Containers: The Stack.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stack: Last In First Out (LIFO).–Used in procedure calls, to compute arithmetic expressions.
Stacks Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
Stacks (and Queues).
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
Stacks 5/2/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
CSCI 3333 Data Structures Stacks.
Data Structures 5th Week
Recap: Solution of Last Lecture Activity
Stacks.
Stacks Chapter 7 introduces the stack data type.
Stacks 9/12/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H.
Stacks Chapter 4.
Data Structures – Week #3
Algorithms and Data Structures
Stacks © 2013 Goodrich, Tamassia, Goldwasser Stacks.
Stacks.
Chapter 5 Stacks and Queues 11/28/2018 Stacks.
Lecture 5 Stacks King Fahd University of Petroleum & Minerals
Stacks 12/7/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H.
Copyright © Aiman Hanna All rights reserved
Recall What is a Data Structure Very Fundamental Data Structures
Stacks and Queues DSA 2013 Stacks n Queues.
Stacks.
Stacks.
Topic 15 Implementing and Using Stacks
Introduction to Stacks
Introduction to Stacks
Data Structures – Week #3
Stacks and Linked Lists
Presentation transcript:

Stacks Stacks

Stack What is a stack? Examples An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO) list. Examples Stacks

Stack Representation Given a stack S = (a0, …, an-1), a0 is the bottom element, an-1 is the top element, and ai is on top of element ai-1, 0 < i < n. a3 a3 a2 a2 a1 a1 a0 a0 Push (Add) Pop (Delete)

Abstract Data Type (ADT) ADT (abstract data type) is an abstraction of a data structure which specifies: Data stored Operations on the data Error conditions associated with operations Example: ADT modeling a simple stock trading system The data stored are buy/sell orders The operations supported are order buy(stock, shares, price) order sell(stock, shares, price) void cancel(order) Error conditions: Buy/sell a nonexistent stock Cancel a nonexistent order Stacks

ADT of Stacks Data Operations Exceptions (Error conditions) Arbitrary objects Operations push(object): inserts an element pop(): removes the last inserted element object top(): returns the last inserted element without removing it integer size(): returns the number of elements stored boolean empty(): indicates if no elements are stored Exceptions (Error conditions) pop() and top() cannot be performed if the stack is empty. push(object) cannot be performed if the stack is full. Stacks

Stack Interface in C++ C++ interface corresponding to our Stack ADT template <typename E> class Stack { public: int size() const; bool empty() const; const E& top() const throw(StackEmpty); void push(const E& e); void pop() throw(StackEmpty); } C++ interface corresponding to our Stack ADT Uses an exception class StackEmpty Different from the built-in C++ STL class stack No change in member variables (for compiler only) More info about const: http://tw.tonytuan.org/2010/03/c-constconst-pointer-pointer-to-const.html Stacks

Applications of Stacks No in textbook Page-visited history in a web browser Undo sequence in a text editor Chain of method calls in the C++ run-time system Infix to postfix conversion Postfix expression evaluation Parenthesis matching HTML tag matching Maze solution finding No in textbook No in textbook Stacks

C++ Run-Time Stack Program counter The C++ run-time system keeps track of the chain of active functions with a stack When a function is called, the system pushes on the stack a frame containing Local variables and return value Program counter, keeping track of the statement being executed When the function ends, its frame is popped from the stack and control is passed to the function on top of the stack Allows for recursion main() { int i = 5; foo(i); } foo(int j) { int k; k = j+1; bar(k); } bar(int m) { … } bar PC = 1 m = 6 foo PC = 3 j = 5 k = 6 main PC = 2 i = 5 Stacks

Array-based Stack Algorithm size() return t + 1 Algorithm pop() if empty() then throw StackEmpty else t  t  1 return S[t + 1] 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 … S 1 2 t Stacks

Array-based Stack (cont.) The array storing the stack elements may become full A push operation will then throw a StackFull exception Algorithm push(obj) if t = S.size()  1 then throw StackFull else t  t + 1 S[t]  obj S 1 2 t … Stacks

Performance and Limitations 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 Stacks

Array-based Stack in C++ template <typename E> class ArrayStack { private: E* S; // array holding the stack int cap; // capacity int t; // index of top element public: // constructor given capacity ArrayStack( int c) : S(new E[c]), cap(c), t(-1) { } void pop() { if (empty()) throw StackEmpty (“Pop from empty stack”); t--; } void push(const E& e) { if (size() == cap) throw StackFull(“Push to full stack”); S[++ t] = e; } … (other methods of Stack interface) Stacks

Example use in C++ ArrayStack<int> A; // A = [ ], size = 0 * indicates top ArrayStack<int> A; // A = [ ], size = 0 A.push(7); // A = [7*], size = 1 A.push(13); // A = [7, 13*], size = 2 cout << A.top() << endl; A.pop(); // A = [7*], outputs: 13 A.push(9); // A = [7, 9*], size = 2 cout << A.top() << endl; // A = [7, 9*], outputs: 9 cout << A.top() << endl; A.pop(); // A = [7*], outputs: 9 ArrayStack<string> B(10); // B = [ ], size = 0 B.push("Bob"); // B = [Bob*], size = 1 B.push("Alice"); // B = [Bob, Alice*], size = 2 cout << B.top() << endl; B.pop(); // B = [Bob*], outputs: Alice B.push("Eve"); // B = [Bob, Eve*], size = 2 Stacks

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

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 Let S be an empty stack for i=0 to 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.empty() then return false {nothing to match with} if S.pop() does not match the type of X[i] then return false {wrong type} return true {every symbol matched} else return false {some symbols were never matched} © 2010 Goodrich, Tamassia Stacks

Expression Evaluation Expressions are converted into postfix notation for evaluation Infix  A/B–C+D*E–A*C Postfix  AB/C-DE*+AC*- Operation Postfix T1 = A / B T1C-DE*+AC*- T2 = T1 - C T2 DE*+AC*- T3 = D * E T2T3+AC*- T4 = T2 + T3 T4AC*- T5 = A * C T4 T5 - T6 = T4 - T5 T6 Stacks

Postfix Notation Advantages of postfix notation Two questions Quiz! Advantages of postfix notation No need to use parentheses No need to consider precedence of operators Two questions How to change infix notation into postfix notation? How to evaluate an expression in postfix notation? Stacks

Infix to Postfix Conversion by Hand Three-pass algorithm: (1) Fully parenthesize expression a / b - c + d * e - a * c  ((((a / b) - c) + (d * e)) - a * c)) (2) All operators replace their corresponding right parentheses. ((((a / b) - c) + (d * e)) – (a * c))) (3) Delete all parentheses. ab/c-de*+ac*-

Rules of Conversion Two rules Operators are taken out of the stack as long as their precedence is higher than or equal to the precedence of the incoming operator. The left parenthesis is placed in the stack whenever it is found in the expression, but it is unstacked only when its matching right parenthesis is found. Stacks

Example: Infix to Postfix The order of operands in infix and postfix are the same. a+b*c  abc*+

Example: Infix to Postfix Quiz! a*(b+c)/d  abc+*d/

More Examples Infix Postfix 2+3*4 a*b+5 (1+2)*7 a*b/c (a/(b- Quiz! Infix Postfix 2+3*4 a*b+5 (1+2)*7 a*b/c (a/(b- c+d))*(e-a)*c a/b- c+d*e- a*c 234*+ ab*5+ 12+7* ab*c/ abc-d+/ ea- *c* ab/c- de*+ac*- Stacks

Walk-through Examples Quiz! a/b-c+d*e-a*c  ab/c-de*+ac*- (a/(b-c+d))*(e-a)*c  abc-d+/ea-*c*

More Examples (a+b)*(c-d)/(e+f)  ab+cd-*ef+/ Quiz! (a+b)*(c-d)/(e+f)  ab+cd-*ef+/ (a+b)*(c-d)/((e-f)*(g+h))  ab+cd-*ef-gh+*/

Evaluating postfix expressions Evaluation process - Make a single left-to-right scan of the expression. - Place the operands on a stack until an operator is found. - Remove, from the stack, the correct numbers of operands for the operator, perform the operation, and place the result back on the stack.

Example of Evaluating postfix expressions

Walk-through Examples a/b-c+d*e-a*c  ab/c-de*+ac*- (a/(b-c+d))*(e-a)*c  abc-d+/ea-*c*

Animation Animation Infix to postfix conversion Postfix evaluation