Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2a. Simple Containers: The Stack.

Slides:



Advertisements
Similar presentations
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title : Overview of Stack.
Advertisements

Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Introduction to Stacks & Queues.
CS 240Chapter 6 - StacksPage 21 Chapter 6 Stacks The stack abstract data type is essentially a list using the LIFO (last-in-first-out) policy for adding.
Chapter 6: Stacks STACK APPLICATIONS STACK IMPLEMENTATIONS CS
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.
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks CS 3358 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
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)
Main Index Contents 11 Main Index Contents Stacks Further Stack Examples Further Stack Examples Pushing/Popping a Stack Pushing/Popping a Stack Class StackClass.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Fundamentals of Python: From First Programs Through Data Structures Chapter 14 Linear Collections: Stacks.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Data Structures: CSCI 362 – Stack Implementation Data Structures: CSCI 362 – Stack Implementation lecture notes adapted from Data Structures with C++ using.
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.
1 Stacks – Chapter 3 A stack is a data structure in which all insertions and deletions of entries are made at one end, called the top of the stack. Alternatively,
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2b. Simple Containers: The Queue.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
Data Structures. The Stack: Definition A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
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)
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part R1. Elementary Data Structures.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
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.
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part R2. Binary Search Trees.
© 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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 CS 132 Spring 2008 Chapter 7 Stacks Read p Problems 1-7.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 19: Stacks and Queues (part 2)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
Data Structures & Algorithms
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 6. Dictionaries(3): Binary Search Trees.
CHP-3 STACKS.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
11/07/141 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the.
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) structure.
Main Index Contents 11 Main Index Contents Stacks Further Stack Examples Further Stack Examples Pushing/Popping a Stack Pushing/Popping a Stack Class StackClass.
Prof. I. J. Chung Data Structure #5 Professor I. J. Chung.
1 Binary Search Trees. 2 Binary Search Trees Binary Search Trees The Binary Search Tree (BST) Search, Insertion and Traversal of BST Removal of nodes.
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.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
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.
1 Data Structures and Algorithms Queue. 2 The Queue ADT Introduction to the Queue data structure Designing a Queue class using dynamic arrays Linked Queues.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2b. Simple Containers: The Queue.
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,
CSCE 210 Data Structures and Algorithms
Chapter 4 Stacks
CSCE 210 Data Structures and Algorithms
CS505 Data Structures and Algorithms
Stacks Stacks.
Stacks Chapter 7 introduces the stack data type.
Stacks.
Stacks Chapter 4.
Algorithms and Data Structures
Stack.
Stacks.
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.
Jordi Cortadella and Jordi Petit Department of Computer Science
Stack.
Presentation transcript:

Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2a. Simple Containers: The Stack

Prof. Amr Goneid, AUC2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks Some Applications of Stacks

Prof. Amr Goneid, AUC3 1. Introduction to the Stack Data Structure  A simple data container consisting of a linear list of elements  Access is by position (order of insertion)  All insertions and deletions are done at one end, called top  Last In First Out (LIFO) structure  Two basic operations: push: add to top, complexity is O(1) pop: remove from top, complexity is O(1)

Prof. Amr Goneid, AUC4 Example

5 Example top ++toptop push pop top top--

Prof. Amr Goneid, AUC6 mukundan/dsal/StackAppl.htmlDemo

Prof. Amr Goneid, AUC7 Run-time stack used in function calls Page-visited history in a Web browser Undo sequence in a text editor Removal of recursion Conversion of Infix to Postfix notation Evaluation of Postfix expressions Reversal of sequences Checking for balanced symbols Some Stack Applications

Prof. Amr Goneid, AUC8 Stack Class Operations construct: construct an empty stack stackIsEmpty  bool : return True if stack is empty stackIsFull  bool : return True if stack is full push(el) : add element (el) at the top pop(el): retrieve and remove the top element stackTop(el): retrieve top element without removing it

Prof. Amr Goneid, AUC9 The stack may be implemented as a dynamic array. The capacity (MaxSize) will be input as a parameter to the constructor (default is 128) The stack ADT will be implemented as a template class to allow for different element types. 2. Array Based Stack Class Definition

Prof. Amr Goneid, AUC10 // File: Stackt.h // Stack template class definition. // Dynamic array implementation #ifndef STACKT_H #define STACKT_H template class Stackt { public: Stackt (int nelements = 128);// Constructor ~Stackt ();// Destructor A Stack Class Definition

Prof. Amr Goneid, AUC11 // Member Functions void push(Type );// Push void pop(Type &);// Pop void stackTop(Type &) const;// retrieve top bool stackIsEmpty() const;// Test for Empty stack bool stackIsFull() const;// Test for Full stack private: Type *stack;// pointer to dynamic array int top, MaxSize; }; #endif // STACKT_H #include "Stackt.cpp" A Stack Class Definition

Prof. Amr Goneid, AUC12 // File: Stackt.cpp // Stack template class implementation #include using namespace std; // Constructor with argument, size is nelements, default is 128 template Stackt ::Stackt(int nelements) { MaxSize = nelements; stack = new Type[MaxSize]; top = -1; } A Stack Class Implementation

Prof. Amr Goneid, AUC13 // Destructor template Stackt ::~Stackt() { delete [ ] stack;} // Push template void Stackt ::push(Type v) { if(stackIsFull()) cout << "Stack Overflow"; else stack[++top] = v; } A Stack Class Implementation

Prof. Amr Goneid, AUC14 // Pop template void Stackt ::pop(Type &v) { if(stackIsEmpty()) cout << "Stack Underflow"; else v = stack[top--]; } A Stack Class Implementation

Prof. Amr Goneid, AUC15 // Retrieve stack top without removing it template void Stackt ::stackTop(Type &v) const { if(stackIsEmpty()) cout << "Stack Underflow"; else v = stack[top]; } A Stack Class Implementation

Prof. Amr Goneid, AUC16 // Test for Empty stack template bool Stackt ::stackIsEmpty() const { return (top < 0); } // Test for Full stack template bool Stackt ::stackIsFull() const { return (top >= (MaxSize-1)); } A Stack Class Implementation

Prof. Amr Goneid, AUC17 int main() // Testing the Stackt Class {// Reverse a string and stack copy Stackt s1; char c; string instring = "Testing Stack Class"; string outstring = ""; cout << instring << endl; int L = instring.length(); cout << "Pushing characters on s1\n"; for (int i = 0; i < L; i++) s1.push(instring.at(i)); cout << "Copying s1 to s2\n"; Stackt s2 = s1; A Driver Program to Test Class

Prof. Amr Goneid, AUC18 cout << "Popping characters from s1\n"; while(!s1.stackIsEmpty()) { s1.pop(c); outstring = outstring + c; } cout << outstring << endl; cout <<"s1 is now empty. Trying to pop from empty s1\n"; s1.pop(c); cout << "Now popping contents of s2" << endl; while(!s2.stackIsEmpty()) { s2.pop(c); cout << c;} cout<< endl; return 0; } A Driver Program to Test Class

Prof. Amr Goneid, AUC19 Output: Testing Stack Class Pushing characters on s1 Copying s1 to s2 Popping characters from s1 ssalC kcatS gnitseT s1 is now empty. Trying to pop from empty s1 Stack Underflow Now popping contents of s2 ssalC kcatS gnitseT Press any key to continue A Driver Program to Test Class

Prof. Amr Goneid, AUC20 A stack can be implemented as a linked structure. Requires more space than array implementations, but more flexible in size. Easy to implement because operations are at the top (in this case the head node) 3. Linked Stacks

Prof. Amr Goneid, AUC21 Node Specification // The linked structure for a node can be // specified as a Class in the private part of // the main stack class. class node// Hidden from user { public: Type e;// stack element node *next;// pointer to next node }; // end of class node declaration typedef node * NodePointer; NodePointer top;// pointer to top

Prof. Amr Goneid, AUC22 Push Operation top First pnew Last New 2 3 push(v): Insert at top NodePointer pnew = new node ; pnew->e = v; pnew->next = top; top = pnew; 1

Prof. Amr Goneid, AUC23 Pop Operation 2 3 cursor top pop(v): Remove from top v = top->e; cursor = top; top = top->next; delete cursor; 1

Prof. Amr Goneid, AUC24 // File: StackL.h // Linked List Stack class definition #ifndef STACKL_H #define STACKL_H template class StackL { public: StackL();// Constructor ~StackL();// Destructor void push(Type );// Push void pop(Type &);// Pop Linked Stack Class

Prof. Amr Goneid, AUC25 void stackTop(Type &) const;// retrieve top bool stackIsEmpty() const;// Test for Empty stack private: // Node Class class node { public: Type e;// stack element node *next;// pointer to next node }; // end of class node declaration Linked Stack Class

Prof. Amr Goneid, AUC26 typedef node * NodePointer; NodePointer top;// pointer to top }; #endif // STACKL_H #include "StackL.cpp" Linked Stack Class

Prof. Amr Goneid, AUC27 Conversion from Decimal to Hexadecimal Balancing Enclosure Symbols Evaluation of Postfix Expressions Converting Infix Expressions to Postfix Computing Spans Backtracking Hanoi Towers 4. Some Applications of Stacks

Prof. Amr Goneid, AUC28 // Covert from Decimal to Hexadecimal string DEC-to_HEX(n) { Stackt s; string H = “”; do {rem = n % 16;n = n / 16; if (rem < 10) c = char (int('0') + rem); else c = char (int('A') + rem - 10); s.push(c); }while ( n != 0); while (!s.stackIsEmpty()) {s.pop(c); H = H + c;} return H; } (a) Decimal to Hexadecimal Conversion

Prof. Amr Goneid, AUC29 Given a text file containing a sequence of characters, we want to check for balancing of the symbols ( ), [ ], { }. Algorithm: bool EnclosureBalance (filename) { Open file filename; Initialize an empty stack of characters; balanced = true; for each character (ch) read until end of file : { If (ch is a left symbol) push ch on the stack; (b) Balancing Enclosure Symbols

Prof. Amr Goneid, AUC30 else if (ch is a right symbol) then if (stack is empty) balanced = false; else { pop the stack; if (popped symbol is not the corresponding left symbol) balanced = false; } At the end of the file, if (stack is not empty) balanced = false; return balanced; } Balancing Enclosure Symbols

Prof. Amr Goneid, AUC31 {a * (b + c) }Balanced {a * (b + c [ i ] }Not Balanced Balancing Enclosure Symbols ( {{{ [ ((( {{{{{

Prof. Amr Goneid, AUC32 Regular expressions are written in “infix” notation, i.e., operator between two operands, e.g., (A+B) * (C- (D+E)) Parentheses are used to force precedence (c) Evaluation of Postfix Expressions

Prof. Amr Goneid, AUC33 Reverse Polish Notation (RPN) or “postfix” does without parentheses (invented by Lukasiewics). e.g. the expression (A+B) * (C- (D+E)) becomes: A B + C D E + - * Postfix expressions like A B + are evaluated as A + B Evaluation of Postfix Expressions

Prof. Amr Goneid, AUC34 The idea is: Scan from left to right until an operator (+,-,*,/) is encountered. Apply operator between the previous operands. Replace the two previous operands by the result. This suggests to use a stack to store operands and the results. Evaluation of Postfix Expressions

Prof. Amr Goneid, AUC35 Initialize a stack (S) of characters For each character from left to right Get next character If operand, push it on S If an operator: –Pop two values (error if there are no two values) –Apply operator –Push result back onto (S) At the end, result is on top of (S) (the only value, otherwise an error) Evaluation of Postfix Expressions (Algorithm)

Prof. Amr Goneid, AUC36 (A+B) * (C- (D+E)) → A B + C D E + - * (2+3)*(2- (4+1)) → * Evaluation of Postfix Expressions (Example) E DDD+E BCCCCC-(D+E) AAA+B Final

Prof. Amr Goneid, AUC37 Initialize an operator stack, s While not end of infix expression do the following: read next symbol in case the symbol is: an operand:write the operand ‘ ( ‘ :push onto s ‘ ) ’ :pop and write all operators until encountering ‘ ( ‘, then pop ‘ ( ‘ ‘ * ’ or ‘ / ’ :1-pop and write all ‘ * ’ and ‘ / ’ operators from the top down to but not including the top most ‘ ( ‘, ’ + ’, ’ - ’ or to the bottom of the stack 2-push the ‘ * ’ or ‘ / ’ ‘ + ’ or ‘ - ’ :1-pop and write all operators from the top down to but not including the topmost ‘ ( ‘ or to the bottom of the stack 2-push the ‘ + ’ or ‘ - ’ End of exp:pop and write all operators (d) Conversion from Infix to Postfix Expression

Prof. Amr Goneid, AUC38 Example: (A+B) * (C- (D+E)) → A B + C D E + - * Conversion from Infix to Postfix Expressions

Prof. Amr Goneid, AUC39 (e) Computing Spans Given an an array X, the span S[i] of X[i] is the maximum number of consecutive elements X[j] immediately preceding and including X[i] and such that X[j] ≤ X[i]. Spans have applications to financial analysis. Example: i X S

Prof. Amr Goneid, AUC40 Computing Spans Algorithm Computing Spans with a Stack Keep in a stack the indices of the elements visible when “looking back”. Scan the array from left to right. Let i be the current index. Pop indices from the stack until stack top = index j such that X[i] < X[j]. Set S[i] ← i − j Push current index i onto the stack

Prof. Amr Goneid, AUC41 Computing Spans Algorithm Linear Algorithm using a Stack spans(X,S, n) { A ← new empty stack for i ← 0 to n − 1 while (!A.stackIsEmpty() && X[A.top()] ≤ X[i] ) A.pop() if (A.stackIsEmpty() ) then S[i] ← i + 1 else S[i] ← i − A.top() A.push(i) }

(f) Backtracking (Maze Problem) Prof. Amr Goneid, AUC42

Prof. Amr Goneid, AUC43 Backtracking (Maze Problem) in out A B C D E FG

Prof. Amr Goneid, AUC44 We may choose to move in the order: South – East – North – West A stack is used to record the tracks. When we move on a new track, we push it on the stack. When we run out of tracks, we backtrack by popping the last track from the stack. Later in the course, we will do this using a recursive algorithm using the system stack. The algorithm is called Depth First Search Backtracking (Maze Problem)

Prof. Amr Goneid, AUC45 The stack will develop as shown Backtracking (Maze Problem) D CCEG BBBBBFF AAAAAAAA steps popexit

(g) The Towers of Hanoi an/dsal/ToHdb.html Prof. Amr Goneid, AUC46

Prof. Amr Goneid, AUC47 Learn on your own about: Use of run-time stack in function calls Removing recursion using a stack