Jordi Cortadella and Jordi Petit Department of Computer Science

Slides:



Advertisements
Similar presentations
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Advertisements

The unorganized person’s data structure
Stacks Example: Stack of plates in cafeteria.
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.
Chapter 6: Stacks STACK APPLICATIONS STACK IMPLEMENTATIONS CS
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.
Topic 15 Implementing and Using Stacks
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.
Infix, Postfix, Prefix.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Topic 15 Implementing and Using Stacks
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
Stacks CS-240 & CS-341 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
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.
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,
CSC 205 Programming II Postfix Expressions. Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
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.
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)
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.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
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)
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
CHP-3 STACKS.
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 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.
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
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.
BCA II Data Structure Using C
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.
CS Data Structures Chapter 6 Stacks Mehmet H Gunes
Stacks Stacks.
COMPSCI 107 Computer Science Fundamentals
Homework 4 questions???.
Stacks Chapter 7 introduces the stack data type.
Stacks Stack: restricted variant of list
Stacks Chapter 4.
Stack application: postponing data usage
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Cs212: Data Structures Computer Science Department Lab 7: Stacks.
Topic 15 Implementing and Using Stacks
CE 221 Data Structures and Algorithms
Containers: Queue and List
Jordi Cortadella Department of Computer Science
Stacks CS-240 Dick Steflik.
Stack.
Jordi Cortadella and Jordi Petit Department of Computer Science
17CS1102 DATA STRUCTURES © 2016 KL University – The contents of this presentation are an intellectual and copyrighted property of KL University. ALL RIGHTS.
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
5.3 Implementing a Stack Chapter 5 – The Stack.
Stacks A stack is an ordered set of elements, for which only the last element placed into the stack is accessible. The stack data type is also known as.
Presentation transcript:

Jordi Cortadella and Jordi Petit Department of Computer Science 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

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

The Stack ADT template <typename T> class Stack { public: … bool empty() const { return data.size() == 0; } 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

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

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

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

From infix to postfix 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

From infix to postfix a + b  c + ( d  e + f )  g a + a + a b Priority  + ( Output a + a + a b Containers: Stacks © Dept. CS, UPC

From infix to postfix a + b  c + ( d  e + f )  g  + a b  + a b c Priority  + (  + a b  + a b c + a b c  + + ( a b c  + Containers: Stacks © Dept. CS, UPC

From infix to postfix a + b  c + ( d  e + f )  g + ( a b c  + d + Priority  + ( + ( a b c  + d + (  a b c  + d + (  a b c  + d e + ( a b c  + d e Containers: Stacks © Dept. CS, UPC

From infix to postfix a + b  c + ( d  e + f )  g + ( a b c  + d e Priority  + ( + ( 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

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

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

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

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

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) Containers: Stacks © Dept. CS, UPC

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

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

Assertions vs. error handling 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

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

Exercises Containers: Stacks © Dept. CS, UPC

Interleaved push/pop operations Suppose that an intermixed sequence of push and pop operations are performed. The pushes push the integers 0 through 9 in order; the pops print out the return value. Which of the following sequences could not occur? 4 3 2 1 0 9 8 7 6 5 4 6 8 7 5 3 2 9 0 1 2 5 6 7 4 8 9 3 1 0 4 3 2 1 0 5 6 7 8 9 Source: Robert Sedgewick, Computer Science 126, Princeton University. Containers: Stacks © Dept. CS, UPC

Middle element of a stack Design the class MidStack implementing a stack with the following operations: Push/pop: the usual operations on a stack. FindMiddle: returns the value of the element in the middle. DeleteMiddle: deletes the element in the middle. All the operations must be executed in O(1) time. Suggestion: use some container of the STL to implement it. Note: if the stack has 𝑛 elements at locations 0..𝑛−1, where 0 is the location at the bottom, the middle element is the one at location (𝑛−1) 2 . Containers: Stacks © Dept. CS, UPC