CENG 213 Data Structures Stacks 5/15/2018 CENG 213.

Slides:



Advertisements
Similar presentations
CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
Advertisements

Stacks Chapter 11.
COSC 2006 Chapter 7 Stacks III
COMPSCI 105 S Principles of Computer Science 13 Stacks.
Chapter 6 Stacks. © 2005 Pearson Addison-Wesley. All rights reserved6-2 ADT Stack Figure 6.1 Stack of cafeteria dishes A stack –Last-in, first-out (LIFO)
CMPT 225 Stacks-part2.
CMPT 225 Stacks.
© 2006 Pearson Addison-Wesley. All rights reserved7 B-1 Chapter 7 (continued) Stacks.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Stacks Chapter Chapter Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions Checking for Balanced Parentheses,
Chapter 6 Stacks. © 2005 Pearson Addison-Wesley. All rights reserved6-2 ADT Stack Figure 6.1 Stack of cafeteria dishes A stack –Last-in, first-out (LIFO)
1 Stacks (Walls & Mirrors - Chapter 6). 2 Overview The ADT Stack Array Implementation of a Stack Linked-List Implementation of a Stack Application Domain:
1 Introduction to Stacks What is a Stack? Stack implementation using array. Stack implementation using linked list. Applications of Stacks.
Chapter 6 Stacks. © 2005 Pearson Addison-Wesley. All rights reserved6-2 The Abstract Data Type Specifications of an abstract data type for a particular.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 6: Stacks Data Abstraction & Problem Solving with C++
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks.
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks (and a bit of generics for flavor)
Comp 245 Data Structures Stacks. What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Chapter 7 Stacks I CS Data Structures I COSC 2006 April 22, 2017
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)
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.
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 6: Stacks Data Abstraction & Problem Solving with C++
Lecture 6: Stacks 1. 2 The Abstract Data Type Specifications of an abstract data type for a particular problem –Can emerge during the design of the problem’s.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
Chapter 6 B Stacks. © 2004 Pearson Addison-Wesley. All rights reserved6 B-2 Comparing Implementations All of the three implementations are ultimately.
Data Structures & Algorithms
Stacks & Queues. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy to use.
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.
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.
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.
6/12/20161 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 The Stack ADT stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) scheme. The last item placed.
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.
Chapter 6 A Stacks. © 2004 Pearson Addison-Wesley. All rights reserved6 A-2 The Abstract Data Type: Developing an ADT During the Design of a Solution.
Data Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
Abstract Data Types (ADTs)
CS Data Structures Chapter 6 Stacks Mehmet H Gunes
Stacks Chapter 6.
Stacks Stacks.
CSCI 3333 Data Structures Stacks.
CC 215 Data Structures Stack ADT
Abstract Data Types (ADTs)
Stacks.
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Stacks Chapter 4.
Data Structures – Week #3
Stack.
Introduction to Data Structures
Chapter 6 Stacks.
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Stacks Chapter 6 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
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.
Stacks Data structure Elements added, removed from one end only
Stacks.
Abstract Data Types (ADTs)
Stack.
Data Structures – Week #3
Chapters 6 and 7 Stacks.
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

CENG 213 Data Structures Stacks 5/15/2018 CENG 213

The Stack Data Structure The Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) scheme. The last item placed on the stack will be the first item removed 5/15/2018 CENG 213

ADT Stack Operations Stack Create an empty stack Destroy a stack Determine whether a stack is empty Add a new item -- push Remove the item that was added most recently -- pop Retrieve the item that was added most recently – top/getTop push pop top Stack 5/15/2018 CENG 213

Implementations of Stack The stack can be implemented using An array A linked list STL list All three implementationscan use exception handling mechanisms to handle possible exceptions 5/15/2018 CENG 213

Implementations of the Stack 2 1 5/15/2018 CENG 213

An Array-Based Implementation of the Data Structure Stack Private data fields An array of items of type Object The index top You can get capacity or there may be a default size for capacity 5/15/2018 CENG 213

An Array-Based Implementation: Header File ##include <string> using namespace std; template <class Object> class Stack { private: int top; int capacity; Object* storage; public: Stack(int capacity); ~Stack(); void push(Object value); Object getTop(); void pop(); bool isEmpty(); }; 5/15/2018 CENG 213

An Array-Based Implementation: Constructor, Destructor Stack::Stack(int cp) { if (cp <= 0) throw string("Stack's capacity must be positive"); storage = new Object[cp]; capacity = cp; top = -1; } Stack::~Stack() { delete[] storage; 5/15/2018 CENG 213

An Array-Based Implementation: push void Stack:push(Object value) { if (top == capacity-1) throw string("Stack's overflown"); top++; storage[top] = value; } bool Stack::isEmpty() { return (top == -1); 5/15/2018 CENG 213

An Array-Based Implementation: getTop, pop Object Stack::getTop() { if (top == -1) throw string("Stack is empty"); return storage[top]; } void Stack::pop() { top--; 5/15/2018 CENG 213

An Array-Based Implementation: main include <iostream> #include "Stack.h” using namespace std; int main() Stack<int> theStack(10); try { theStack.push(i);} catch(string s) {cout << s << endl;} try{ cout << theStack.getTop() << endl; theStack.pop(); } } return 0; } 5/15/2018 CENG 213

A Pointer-Based Implementation of the ADT Stack Required when the stack needs to grow and shrink dynamically top is a reference to the head of a linked list of items (You can implement it with or without a header node) A copy constructor and destructor must be supplied 5/15/2018 CENG 213

A Pointer-Based Implementation: Header File template <class Object> class StackNode { public: StackNode(const Object& e = Object(), StackNode* n = NULL) : element(e), next(n) {} Object element; StackNode* next; }; 5/15/2018 CENG 213

A Pointer-Based Implementation: Header File template <class Object> class StackDyn { public: StackDyn(); ~StackDyn(); void push(Object data); Object getTop() throw(string); void pop() throw(string); bool isEmpty() Private: StackNode<Object> *top; int count; }; 5/15/2018 CENG 213

A Pointer-Based Implementation: Constructor and Destructor StackDyn::StackDyn() { top = new StackNode<Object>; count=0; } StackDyn::~StackDyn() while (!isEmpty()) pop(); delete top; 5/15/2018 CENG 213

A Pointer-Based Implementation: push void StackDyn::push(Object data) { StackNode<Object>* newTop = new StackNode<Object>; newTop->element = data; newTop->next = top->next; top->next = newTop; count++; } 5/15/2018 CENG 213

A Pointer-Based Implementation: getTop and pop Object StackDyn::getTop() throw(string) { if (count == 0) throw string("Stack is empty"); return top->next->element; } void pop() throw(string){ if(count == 0) else{ StackNode<Object>* old = top->next; top->next = old->next; count--; delete old; } } 5/15/2018 CENG 213

An Implementation That Uses the ADT List The ADT list can be used to represent the items in a stack If the item in position 1 is the top push(newItem) insert(newItem, zeroth()) pop() remove(first()->element) getTop() first()->element 5/15/2018 CENG 213

Comparing Implementations Fixed size versus dynamic size An array-based implementation Prevents the push operation from adding an item to the stack if the stack’s size limit has been reached A pointer-based implementation Does not put a limit on the size of the stack An implementation that uses a linked list versus one that uses a pointer-based implementation of the ADT list Linked list approach is more efficient ADT list approach reuses an already implemented class Much simpler to write Saves time When the ADT stack is used to solve a problem, the use of the ADT’s operations should not depend on its implementation 5/15/2018 CENG 213

A Simple Stack Application: Undo sequence in a text editor Problem: abcd fg   abf // Reads an input line. Enter a character or a backspace character ()‏ readAndCorrect(out aStack:Stack)‏ aStack.createStack()‏ read newChar while (newChar is not end-of-line symbol) { if (newChar is not backspace character)‏ aStack.push(newChar)‏ else if (!aStack.isEmpty())‏ aStack.pop()‏ } 5/15/2018 CENG 213

A Simple Stack Application: Display Backward Display the input line in reversed order by writing the contents of stack, named aStack. displayBackward(in aStack:Stack)‏ while (!aStack.isEmpty())) { aStack.pop(newChar)‏ write newChar } 5/15/2018 CENG 213

Checking for Balanced Braces A stack can be used to verify whether a program contains balanced braces An example of balanced braces abc{defg{ijk}{l{mn}}op}qr An example of unbalanced braces abc{def}}{ghij{kl}m Requirements for balanced braces Each time we encounter a “}”, it matches an already encountered “{” When we reach the end of the string, we have matched each “{” 5/15/2018 CENG 213

Checking for Balanced Braces 11/20/08 5/15/2018 CENG 213

Checking for Balanced Braces: Algorithm aStack.createStack(); balancedSoFar = true; i=0; while (balancedSoFar and i < length of aString) { ch = character at position i in aString; i++; if (ch is ‘{‘) // push an open brace aStack.push(‘{‘); else if (ch is ‘}’) // close brace if (!aStack.isEmpty())‏ aStack.pop(); // pop a matching open brace else // no matching open brace balancedSoFar = false; // ignore all characters other than braces } if (balancedSoFar and aStack.isEmpty())‏ aString has balanced braces else aString does not have balanced braces 5/15/2018 CENG 213

Recognizing Strings in a Language L = {w$w’ : w is a possible empty string of characters other than $, w’ = reverse(w) } abc$cba, a$a, $ are in the language L abc$abc, a$b, a$ are not in the language L Problem: Deciding whether a given string in the language L or not. A solution using a stack Traverse the first half of the string, pushing each character onto a stack Once you reach the $, for each character in the second half of the string, match a popped character off the stack 5/15/2018 CENG 213

Recognizing Strings in a Language -- Algorithm aStack.createStack(); i=0; ch = character at position i in aString; while (ch is not ‘$’) { // push the characters before $ (w) onto the stack aStack.push(ch); i++; ch = character at position i in aString; } i++; inLanguage = true; // skip $; assume string in language while (inLanguage and i <length of aString) // match the reverse of if (aStack.isEmpty()) inLanguage = false; // first part shorter than second part else { aStack.pop(stackTop); ch = character at position i in aString; if (stackTop equals to ch) i++; // characters match else inLanguage = false; // characters do not match if (inLanguage and aStack.isEmpty())‏ aString is in language else aString is not in language 5/15/2018 CENG 213

Application: Algebraic Expressions Infix/Postfix/Prefix Notation: (consider conventional priority ordering among arithmetical operations)‏ 2 + 4 * 5 -8 / 4 (infix)‏ 2 4 5 * + 8 4 / - (postfix – reverse polish notation)‏ - + * 4 5 2 / 8 4 (prefix – polish notation)‏ postfix/prefix no need for parenthesis and priority rules 5/15/2018 CENG 213

Application: Algebraic Expressions To evaluate an infix expression Convert the infix expression to postfix form Evaluate the postfix expression Infix Expression Postfix Expression 5 + 2 * 3 5 2 3 * + 5 * 2 + 3 5 2 * 3 + 5 * ( 2 + 3 ) - 4 5 2 3 + * 4 - 5/15/2018 CENG 213

Evaluating Postfix Expressions When an operand is entered, the calculator Pushes it onto a stack When an operator is entered, the calculator Applies it to the top two operands of the stack Pops the operands from the stack Pushes the result of the operation on the stack 5/15/2018 CENG 213

Evaluating Postfix Expressions 5/15/2018 CENG 213

Converting Infix Expressions to Postfix Expressions Facts about converting from infix to postfix Operands always stay in the same order with respect to one another An operator will move only “to the right” with respect to the operands All parentheses are removed 5/15/2018 CENG 213

Converting Infix Expressions to Postfix Expressions Infix to Postfix Conversion: start reading chars until the end of expression if a right parenthesis, pop and write until a left parenthesis if an operator, pop and write until a lower precedence operator is seen, then push the operator if an operand, write if left parenthesis, push pop the stack and write until empty 5/15/2018 CENG 213

Converting Infix Expressions to Postfix Expressions Infix to Postfix Conversion: e.g. 2 + 4 * 5 -8 / 4 a+ b * c + (d * e + f) * g 5/15/2018 CENG 213

Converting Infix Expr. to Postfix Expr.: Algorithm for (each character ch in the infix expression) { switch (ch) { case operand: // append operand to end of postfixExpr postfixExpr=postfixExpr+ch; break; case ‘(‘: // save ‘(‘ on stack aStack.push(ch); break; case ‘)’: // pop stack until matching ‘(‘, and remove ‘(‘ while (top of stack is not ‘(‘) { postfixExpr=postfixExpr+(top of stack); aStack.pop(); } aStack.pop(); break; 5/15/2018 CENG 213

Converting Infix Expr. to Postfix Expr.: Algorithm case operator: // process stack operators of greater precedence while (!aStack.isEmpty() and top of stack is not ‘(‘ and precedence(ch) <= precedence(top of stack) ) { postfixExpr=postfixExpr+(top of stack); aStack(pop); } aStack.push(); break; // save new operator } } // end of switch and for // append the operators in the stack to postfixExpr while (!isStack.isEmpty()) { aStack(pop); 5/15/2018 CENG 213

Converting Infix Expressions to Postfix Expressions a - (b + c * d)/ e  a b c d * + e / - 5/15/2018 CENG 213

Application: A Search Problem Problem: For each customer request, indicate whether a sequence of flights exists from the origin city to the destination city The flight map is a directed graph Adjacent vertices are two vertices that are joined by an edge A directed path is a sequence of directed edges A Flight Map 5/15/2018 CENG 213

A Nonrecursive Solution That Uses a Stack The solution performs an exhaustive search Beginning at the origin city, the solution will try every possible sequence of flights until either It finds a sequence that gets to the destination city It determines that no such sequence exists Backtracking can be used to recover from a wrong choice of a city 5/15/2018 CENG 213

A Nonrecursive Solution - Trace P is origin city; Z is destination city 5/15/2018 11/20/08 CENG 213

A Nonrecursive Solution -- Algorithm searchS(in originCity:City, in destinationCity:City) : boolean // searches for a sequence of flights from originCity to destinationCity aStack.createStack(); clear marks on all cities; aStack.push(originCity); mark origin as visited; while (!aStack.isEmpty() and destinationCity is not at top of stack) { if (no flights exist from city on top of stack to unvisited cities)‏ aStack.pop(); // backtrack else { select an unvisited destination city C for a flight from city on top of stack; aStack.push(C); mark C as visited; }} if (aStack.isEmpty()) return false; // no path exists else return true; // path exists 5/15/2018 CENG 213

A Recursive Solution for Search Problem searchR(in originCity:City, in destinationCity:City):boolean mark originCity as visited; if (originCity is destinationCity) Terminate -- the destination is reached else for (each unvisited city C adjacent to originCity) searchR(C, destinationCity); 5/15/2018 CENG 213

The Relationship Between Stacks and Recursion A strong relationship exists between recursion and stacks Typically, stacks are used by compilers to implement recursive methods During execution, each recursive call generates an activation record that is pushed onto a stack Stacks can be used to implement a nonrecursive version of a recursive algorithm 5/15/2018 CENG 213

C++ Runtime Stack main i = 5 foo j = 5 k = 6 bar m = 6 The C++ run-time system keeps track of the chain of active functions with a stack When a function is called, the run-time system pushes on the stack a frame containing Local variables and return value When a function returns, its frame is popped from the stack and control is passed to the method on top of the stack main() { int i = 5; foo(i); } foo(int j) { int k; k = j+1; bar(k); } bar(int m) { … } Run-time Stack 5/15/2018 CENG 213

Stacks -- Summary ADT stack operations have a last-in, first-out (LIFO) behavior There are different stack implementations Two Major Implementations: Array-Based, Pointer-Based Many stack applications expression processing language recognition search problem A strong relationship exists between recursion and stacks Any recursive program can be rewritten as a nonrecursive program using stacks. 5/15/2018 CENG 213