the Stack stack ADT using the STL stack are parentheses balanced? algorithm uses a stack adapting the STL vector class adapting the STL list class

Similar documents
the Queue queue ADT using the STL queue designing the simulation simulation with STL queue using STL list as queue using STL vector as queue

CSC 222: Computer Programming II. Spring 2004

Abstract Data Types 1

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11.

Abstract Data Types. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Templates and Vectors

Abstract Data Types 1

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

Programming Abstractions

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

Lists. linking nodes. constructors. chasing pointers. MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010.

Topics. bool and string types input/output library functions comments memory allocation templates classes

STACKS AND QUEUES. Problem Solving with Computers-II

Priority Queues and Huffman Trees

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

CS 106B Lecture 5: Stacks and Queues

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT

Expression Trees and the Heap

Graphs. directed and undirected graphs weighted graphs adjacency matrices. abstract data type adjacency list adjacency matrix

Queue Implementations

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Stack Applications. parsing a postfix expression evaluating postfix expressions. converting infix sums from infix to postfix

Iterators. node UML diagram implementing a double linked list the need for a deep copy. nested classes for iterator function objects

CSCE 110 PROGRAMMING FUNDAMENTALS

STL: C++ Standard Library

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming

Hashing. mapping data to tables hashing integers and strings. aclasshash_table inserting and locating strings. inserting and locating strings

Data Structures and Algorithms

Stacks. Revised based on textbook author s notes.

Review: Expressions, Variables, Loops, and more.

CIS Fall Data Structures Midterm exam 10/16/2012

Hashing. inserting and locating strings. MCS 360 Lecture 28 Introduction to Data Structures Jan Verschelde, 27 October 2010.

Midterm Practice TA: Brian Choi Section Webpage:

selectors, methodsinsert() andto_string() the depth of a tree and a membership function

Chapter 7: Stacks. Exercises 7.2

STL Standard Template Library

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

Unified Modeling Language a case study

Getting started with C++ (Part 2)

CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions

CSI33 Data Structures

September 19,

Largest Online Community of VU Students

COEN244: Class & function templates

Data Abstraction and Specification of ADTs

More Group HW. #ifndef Stackh #define Stackh. #include <cstdlib> using namespace std;

Introduction to Programming

Simulations. buffer of fixed capacity using the STL deque. modeling arrival times generating and processing jobs

Computer Programming

Quadratic Sorting Algorithms

Binary Search. the towers of Hanoi recursive C++ code. sorted vectors of numbers fast power function. when not to use recursion memoization

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements

Data Structures and Algorithms

CS 171: Introduction to Computer Science II. Stacks. Li Xiong

Template based set of collection classes STL collection types (container types)

Unit 4: Stacks and Queues

The Stack and Queue Types

Programming Abstractions

Elements of C in C++ data types if else statement for loops. random numbers rolling a die

08 STACKS DATA STRUCTURES AND ALGORITHMS IMPLEMENTATION & APPLICATIONS IMRAN IHSAN ASSISTANT PROFESSOR, AIR UNIVERSITY, ISLAMABAD

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

1 Unit 8 'for' Loops

Review Questions for Final Exam

Linked List using a Sentinel

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

ADTs: Stacks and Queues

CSCI-1200 Computer Science II Fall 2008 Lecture 15 Associative Containers (Maps), Part 2

1 #include <iostream> 2 using namespace std; 3 4 // implementing the dynamic List ADT using Linked List 5 6 class Node{ 7 8 private: 9 int data; 10

Welcome to MCS 360. content expectations. using g++ input and output streams the namespace std. Euclid s algorithm the while and do-while statements

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Why Is Repetition Needed?

C++ Programming: From Problem Analysis to Program Design, Third Edition

ECE Spring 2018 Problem Set #0 Due: 1/30/18

Computer Programming

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.

March 13/2003 Jayakanth Srinivasan,

Programming Abstractions

Data Structures using OOP C++ Lecture 9

CPSC 427: Object-Oriented Programming

COMP 250. Lecture 8. stack. Sept. 25, 2017

Introduction to Programming EC-105. Lecture 2

Unit 7. 'while' Loops

DATA STRUCTURES AND ALGORITHMS LECTURE 08 QUEUES IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD

Fundamentals of Programming CS-110. Lecture 2

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Programming in C++: Assignment Week 1

Programming Language. Functions. Eng. Anis Nazer First Semester

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.

Stack and Its Implementation

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Lecture 7. Log into Linux New documents posted to course webpage

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

Software Design Abstract Data Types

REPETITION CONTROL STRUCTURE LOGO

Stack Abstract Data Type

Local and Global Variables

SSE2034: System Software Experiment 3

COMP6771 Advanced C++ Programming

Transcription:

the Stack 1 The Stack Abstract Data Type stack ADT using the STL stack 2 An Application: Test Expressions are parentheses balanced? algorithm uses a stack 3 Stack Implementations adapting the STL vector class adapting the STL list class MCS 360 Lecture 13 Introduction to Data Structures Jan Verschelde, 27 September 2017 Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 1 / 24

the Stack 1 The Stack Abstract Data Type stack ADT using the STL stack 2 An Application: Test Expressions are parentheses balanced? algorithm uses a stack 3 Stack Implementations adapting the STL vector class adapting the STL list class Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 2 / 24

stacks A stack is a LIFO (Last In First Out) sequence: we can only get (or pop) the element on top. Despite this restriction, many applications: parsing expressions, store information about function calls. In the STL, a stack is an adapter: either a vector or a list implements a stack. Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 3 / 24

stack ADT abstract <typename T> stack; /* a stack is a sequence of elements, stored as Last In First Out (LIFO) */ abstract bool empty ( stack s ); postcondition: empty(s) == true if s is empty, == false if s is not empty; abstract T pop ( stack s ); precondition: not empty(s); postcondition: push(s,pop(s)) == s; abstract void push ( stack s, T e ); postcondition: push(s,e); pop(s) == e; Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 4 / 24

the Stack 1 The Stack Abstract Data Type stack ADT using the STL stack 2 An Application: Test Expressions are parentheses balanced? algorithm uses a stack 3 Stack Implementations adapting the STL vector class adapting the STL list class Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 5 / 24

using the STL stack #include <iostream> #include <stack> using namespace std; int main() { stack<int> s; int e; do { cout << "give element (0 to stop) : "; cin >> e; if(e <= 0) break; s.push(e); } while(true); Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 6 / 24

top and pop while(!s.empty()) { int e = s.top(); s.pop(); cout << "popped " << e << endl; } Members of stack<t> class: T top() const : returns the top of the stack, void pop() : removes the top element. Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 7 / 24

the Stack 1 The Stack Abstract Data Type stack ADT using the STL stack 2 An Application: Test Expressions are parentheses balanced? algorithm uses a stack 3 Stack Implementations adapting the STL vector class adapting the STL list class Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 8 / 24

problem statement Given an expression (w*(x+y) / z - (p/(9-8))), test if every closing bracket ) matches an opener (. Simple counting algorithm: +1 if encounter opener (, and 1 if encounter closer ). Expression is balanced if final count equals zero. Harder if different type of brackets, braces, and parentheses can be used, e.g.: (w*[x+y] / z - [p/{9-8}]). Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 9 / 24

running the program $ /tmp/match_brackets give an expression : (w*[x+y] / z - [p/{9-8}]) checking "(w*[x+y] / z - [p/{9-8}])"... pushed ( pushed [ ] matches [ popped [ pushed [ pushed { } matches { popped { ] matches [ popped [ ) matches ( popped ( parenthesis in "(w*[x+y] / z - [p/{9-8}])" \ are balanced $ Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 10 / 24

the Stack 1 The Stack Abstract Data Type stack ADT using the STL stack 2 An Application: Test Expressions are parentheses balanced? algorithm uses a stack 3 Stack Implementations adapting the STL vector class adapting the STL list class Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 11 / 24

algorithm uses a stack A stack stores all opening brackets: we push every opening bracket, for every matching closing bracket, we pop. For every character c in a given expression: if c is (, {, or [ then push c to a stack else if c is ), }, or ] then if top of stack matches c then pop the stack else break out of loop: parenthesis unbalanced. Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 12 / 24

data and variables #include <iostream> #include <string> #include <stack> using namespace std; int main() { string expression; cout << "give an expression : "; getline(cin,expression, \n ); stack<char> brackets; string opening_brackets = "({["; string closing_brackets = ")}]"; Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 13 / 24

recall the find For any string s and character c: s.find(c) either or returns string::npos if c does not occur in s, returns the first index k for which s[k] == c. We use find with c == expression[i] on s == opening_brackets or s == closing_brackets. Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 14 / 24

pushing and popping bool balanced = true; for(int i=0; i<expression.size(); i++) if(opening_brackets.find(expression[i])!= string::npos) brackets.push(expression[i]); else if(closing_brackets.find(expression[i])!= string::npos) { int k = closing_brackets.find(expression[i]); char c = brackets.top(); if(c!= opening_brackets[k]) { balanced = false; break; } else brackets.pop(); } Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 15 / 24

the Stack 1 The Stack Abstract Data Type stack ADT using the STL stack 2 An Application: Test Expressions are parentheses balanced? algorithm uses a stack 3 Stack Implementations adapting the STL vector class adapting the STL list class Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 16 / 24

adapting STL vectors A stack is said to be an adapter class: we adapt a sequential container, get a stack implementation providing another interface to vector or list. A dictionary between STL stack and vector, for any item t of type T: stack<t> s s.push(t) if(!s.empty()) t = s.top() t = s.top() s.pop() vector<t> v v.push_back(t) if(!v.empty()) t = v[v.size()-1] t = v.back() v.pop_back() Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 17 / 24

STL vector as stack #include <iostream> #include <vector> using namespace std; int main() { vector<int> s; int e; do { cout << "give element (0 to stop) : "; cin >> e; if(e <= 0) break; s.push_back(e); } while(true); Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 18 / 24

top and pop while(!s.empty()) { int e = s[s.size()-1]; cout << "popped " << e << " = " << s.back() << endl; s.pop_back(); } A stack is a natural data structure to reverse the order in any sequence. Application: check if word is a palindrome. A palindrome can be read forward and backward, some examples: dad, testset, racecar. Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 19 / 24

the Stack 1 The Stack Abstract Data Type stack ADT using the STL stack 2 An Application: Test Expressions are parentheses balanced? algorithm uses a stack 3 Stack Implementations adapting the STL vector class adapting the STL list class Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 20 / 24

adapting STL lists As an alternative to adapting the STL vector class, we can implement a stack adapting the STL list class. A dictionary between STL stack and list, for any item t of type T: stack<t> s s.push(t) if(!s.empty()) t = s.top() s.pop() List<T> L L.push_back(t) if(!l.empty()) t = L.back() v.pop_back() Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 21 / 24

STL list as stack #include <iostream> #include <list> using namespace std; int main() { list<int> s; int e; do { cout << "give element (0 to stop) : "; cin >> e; if(e <= 0) break; s.push_back(e); } while(true); Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 22 / 24

top and pop while(!s.empty()) { int e = s.back(); s.pop_back(); cout << "popped " << e << endl; } Observe that the uniform naming of methods in STL leads to another type of generic programming: in the description of the algorithm, we may declare s as vector<t> s, oraslist<t> s. Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 23 / 24

Summary + Exercises Started Chapter 5 on Stacks. Although simpler than vectors or lists, some algorithms reduce to mere loops with a stack. Exercises: 1 Write code using a stack to test if a string, given by the user, is a palindrome. 2 The phrase "murder for a jar of red rum" is a palindrome. Adjust the code of the first exercise to ignore spaces. 3 Adjust the test for balanced parentheses to match single (left and right ) and double quotes ". 4 Use a stack to compute the value of a number given as string in some given basis (< 10). For example: "537" in octal (base 8) evaluates to 7 + 3 8 + 5 8 2. Introduction to Data Structures (MCS 360) the Stack L-13 27 September 2017 24 / 24