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

Similar documents
Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT

Containers: Queue and List. Jordi Cortadella and Jordi Petit Department of Computer Science

STACKS AND QUEUES. Problem Solving with Computers-II

Stacks and their Applications

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

[CS302-Data Structures] Homework 2: Stacks

Data Structures and Algorithms

CSC 222: Computer Programming II. Spring 2004

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.

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

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

An Introduction to Trees

Abstract Data Types 1

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

March 13/2003 Jayakanth Srinivasan,

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

Top of the Stack. Stack ADT

Containers: Priority Queues. Jordi Cortadella and Jordi Petit Department of Computer Science

Containers: Priority Queues

Top of the Stack. Stack ADT

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

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

Stacks. Revised based on textbook author s notes.

Abstract Data Types 1

List, Stack, and Queues

The Stack and Queue Types

Stacks, Queues (cont d)

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

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1

09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

Programming Abstractions

Stacks Fall 2018 Margaret Reid-Miller

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

Lecture No.04. Data Structures

ABSTRACT DATA TYPES (ADTS) COMP1927 Computing 2 16x1 Sedgewick Chapter 4

CS W3134: Data Structures in Java

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

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5

CMPT 225. Lecture 9 Stack

Stack and Its Implementation

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

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

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.

Lecture Data Structure Stack

Data Structures using OOP C++ Lecture 9

Programming Abstractions

CS 206 Introduction to Computer Science II

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

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

Data Structures And Algorithms

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

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

Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016

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

CSE143 Exam with answers Problem numbering may differ from the test as given. Midterm #2 February 16, 2001

Stacks, Queues and Hierarchical Collections

ADT: Design & Implementation

Stacks. CONTENTS 3.1 Introduction 1. Stack as an abstract data type 2. Representation of a Stack as an array 3.2Applications of Stack.

Data Structures and Algorithms

Formal Languages and Automata Theory, SS Project (due Week 14)

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

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms

CS 211 Programming Practicum Fall 2018

Dynamic Data Structures

Arrays and Linked Lists

Outline. Stacks. 1 Chapter 5: Stacks and Queues. favicon. CSI33 Data Structures

CMPT 125: Practice Midterm Answer Key

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

12 Abstract Data Types

Lecture 12 ADTs and Stacks

Review: Expressions, Variables, Loops, and more.

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

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

CHAPTER 3 STACKS AND QUEUES. Iris Hui-Ru Jiang Fall 2008

CS 211 Programming Practicum Spring 2018

ADTs Stack and Queue. Outline

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

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

CS302 Data Structures using C++

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

Instantiation of Template class

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

SimpleCalc. which can be entered into a TI calculator, like the one on the right, like this:

Link-Based Implementations. Chapter 4

CS24 Week 4 Lecture 2

CS 206 Introduction to Computer Science II

The C++ Object Lifecycle. EECS 211 Winter 2019

Introduction to Computer and Program Design 2. Lesson 6. Stacks. James C.C. Cheng Department of Computer Science National Chiao Tung University

Stack Abstract Data Type

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

1. Stack Implementation Using 1D Array

Linear Data Structure

! A data type for which: ! An ADT may be implemented using various. ! Examples:

CSC 222: Computer Programming II. Spring 2005

Outline. Introduction to Programming (in C++) Algorithms on sequences. Reasoning about loops: Invariants. Maximum of a sequence. Maximum of a sequence


Types of Data Structures

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

Transcription:

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

The Stack ADT A stack is a list of objects in which insertions and deletions can only be performed at the top of the list. Also known as LIFO (Last In, First Out) push (insert an element at the top) pop (delete the most recently inserted element) 8 3 5 1 6 top (the most recently inserted element) empty (is there any element?) Note: pop and top generate an error on an empty stack Containers: Stacks Dept. CS, UPC 2

The Stack ADT template <typename T> class Stack { public: // Default constructor Stack() { private: vector<t> data; ; The definition can handle generic stacks of any type T. The default constructor does not need to do anything: a zero-sized vector is constructed by default. Containers: Stacks Dept. CS, UPC 3

template <typename T> class Stack { public: bool empty() const { return data.size() == 0; The Stack ADT const T& top() const { // Returns a const reference assert (not empty()); return data.back(); T& top() { // Returns a reference assert (not empty()); return data.back(); void pop() { assert (not empty()); data.pop_back(); ; void push(const T& x) { data.push_back(x); Containers: Stacks Dept. CS, UPC 4

Balancing symbols Balancing symbols: check for syntax errors when expressions have opening/closing symbols, e.g., () [] { Correct: [(){()[()]()] Incorrect: [(){( Algorithm (linear): read all chars until end of file. For each char, do the following: If the char is opening, push it onto the stack. If the char is closing and stack is empty error, otherwise pop a symbol from the stack and check they match. If not error. At the end of the file, check the stack is empty. Exercise: implement and try the above examples. Containers: Stacks Dept. CS, UPC 5

Evaluation of postfix expressions This is an infix expression. What s his value? 42 or 968? 8 * 3 10 2 * 4 It depends on the operator precedence. For scientific calculators, * has precedence over. Postfix (reverse Polish notation) has no ambiguity: 8 3 * 10 2 4 * Postfix expressions can be evaluated using a stack: each time an operand is read, it is pushed on the stack each time an operator is read, the two top values are popped and operated. The result is push onto the stack Containers: Stacks Dept. CS, UPC 6

Evaluation of postfix expressions: example 6 5 2 3 8 * 3 * 3 2 5 6 5 5 6 8 5 5 6 40 5 6 45 6 3 45 6 48 6 288 push(6) push(5) push(2) push(3) push(8) * push(3) * Containers: Stacks Dept. CS, UPC 7

From infix to postfix a b * c ( d * e f ) * g a b c * d e * f g * Algorithm: When an operand is read, write it to the output. If we read a right parenthesis, pop the stack writing symbols until we encounter the left parenthesis. For any other symbol (, *, (), pop entries and write them until we find an entry with lower priority. After popping, push the symbol onto the stack. Exception: ( can only be removed when finding a ). When the end of the input is reached, all symbols in the stack are popped and written onto the output. Containers: Stacks Dept. CS, UPC 8

From infix to postfix a b * c ( d * e f ) * g Output a a a b Containers: Stacks Dept. CS, UPC 9

From infix to postfix a b * c ( d * e f ) * g * a b * a b c a b c * ( a b c * Containers: Stacks Dept. CS, UPC 10

From infix to postfix a b * c ( d * e f ) * g ( * ( a b c * d a b c * d * ( ( a b c * d e a b c * d e * Containers: Stacks Dept. CS, UPC 11

From infix to postfix a b * c ( d * e f ) * g ( a b c * d e * f a b c * d e * f * a b c * d e * f * a b c * d e * f g Containers: Stacks Dept. CS, UPC 12

From infix to postfix a b * c ( d * e f ) * g a b c * d e * f g * Complexity: O(n) Suggested exercise: Add substraction (same priority as addition) and division (same priority as multiplication). Containers: Stacks Dept. CS, UPC 13

The Stack ADT with pointers head top A B C push(x) head top X A B C head (empty stack) Containers: Stacks Dept. CS, UPC 14

The Stack ADT with pointers template <typename Type> class Stack { private: // The internal cell to represent a node struct Node { Type elem; // Data Node* next; // pointer to the next element ; ; Node* head; // Pointer to the top of the stack int n; // Number of elements Containers: Stacks Dept. CS, UPC 15

The Stack ADT with pointers public: int size() const { return n; bool empty() const { return size() == 0; // or also head == nullptr void push(const Type& x) { head = new Node{x, head; n; void pop() { assert(not empty()); Node* old = head; head = head->next; delete old; --n; // Returns a copy Type top() const { assert(not empty()); return head->elem; // Returns a reference Type& top() { assert(not empty()); return head->elem; // Returns a const reference const Type& top() const { assert(not empty()); return head->elem; Containers: Stacks Dept. CS, UPC 16

The Stack ADT with pointers: usage Stack<Person> S; // Empty stack Person p( MyName, myage); S.push(p); Person q1 = S.top(); // Makes a copy Person& q2 = S.top(); // Ref to the top const Person& q3 = S.top(); // Const ref to the top q1.name = newname ; // Only local copy modified q2.name = newname ; // Top of the stack modified q3.name = newname ; // Illegal (q3 is const) q2 = q1; // Illegal: references cannot be modified Containers: Stacks Dept. CS, UPC 17

The Stack ADT with pointers private: // Recursive copy of the elements. // Exercise: design an iterative version. Node* copy(node* p) { if (p) return new Node{p->elem, copy(p->next); else return nullptr; // Recursive deallocation of the elements void free(node* p) { if (p) { free(p->next); delete p; Containers: Stacks Dept. CS, UPC 18

The Stack ADT with pointers public: // Default constructor (empty stack) Stack() : head(nullptr), n(0) { // Copy constructor Stack(const Stack& s) : head(copy(s.head)), n(s.n) { // Assignment constructor Stack& operator= (const Stack& s) { if (&s!= this) { // Make a new copy only if different free(head); head = copy(s.head); n = s.n; return *this; // Must return a ref to the object // Destructor ~Stack() { free(head); Containers: Stacks Dept. CS, UPC 19

Assertions vs. error handling Assertions: Runtime checks of properties (e.g., invariants, pre-/post-conditions). Useful to detect internal errors. They should always hold in a bug-free program. They should give meaningful error messages to the programmers. Error handling: Detect improper use of the program (e.g., incorrect input data). The program should not halt unexpectedly. They should give meaningful error messages to the users. Containers: Stacks Dept. CS, UPC 20

Assertions vs. error handling assert (x >= 0); double y = sqrt(x); assert (i >= 0 and i < A.size()); int v = A[i]; assert (p!= nullptr); int n = p->number; string id; cin >> id; if (isdigit(name[0])) { cerr << Invalid identifier << endl; return false; Containers: Stacks Dept. CS, UPC 21