Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.

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, Queues, and Linked Lists
CSCE 3110 Data Structures & Algorithm Analysis Stacks and Queues Reading: Chap.3 Weiss.
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
The unorganized person’s data structure
COSC 2006 Chapter 7 Stacks III
Lec 7 Sept 17 Finish discussion of stack infix to postfix conversion Queue queue ADT implementation of insert, delete etc. an application of queue.
More on Stacks and Queues. As we mentioned before, two common introductory Abstract Data Type (ADT) that worth studying are Stack and Queue Many problems.
CS 206 Introduction to Computer Science II 03 / 04 / 2009 Instructor: Michael Eckmann.
Queue Overview Queue ADT Basic operations of queue
Chapter 3 1. Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can.
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.
Stack and Queue COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
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.
E.G.M. Petrakisstacks, queues1 Stacks  Stack: restricted variant of list  elements may by inserted or deleted from only one end : LIFO lists  top: the.
Stacks and Queues COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
CS 206 Introduction to Computer Science II 03 / 06 / 2009 Instructor: Michael Eckmann.
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 Feb 19 Goals: l subset generation program (related to lab # 3) l applications of stack l Postfix expression evaluation l Convert infix to postfix.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Lecture 8 Feb 19 Goals: l applications of stack l Postfix expression evaluation l Convert infix to postfix l possibly start discussing queue.
Stacks and Queues.
Stacks and Queues. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor.
Lecture 11 Sept 26, 2011 Goals convert from infix to postfix.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
CS 206 Introduction to Computer Science II 10 / 28 / 2009 Instructor: Michael Eckmann.
Definition Stack is an ordered collection of data items in which access is possible only at one end (called the top of the stack). Stacks are known.
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
Exam 1 –Monday June 25 th –open Book / Open Notes –No Electronic Devices (calculators, laptops, etc) –Room Number: W –Time: 5:30pm to 8:00pm.
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 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 7 Stacks I CS Data Structures I COSC 2006 April 22, 2017
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.
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.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Data Structures & Algorithms
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
CHP-3 STACKS.
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.
Stacks & Queues CSC 172 SPRING 2002 LECTURE 4 Agenda  Stack  Definition  Implementation  Analysis  Queue  Definition  Implementation  Analysis.
Computer Science Department Data Structure and Algorithms Lecture 3 Stacks.
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.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
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.
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.
Stacks Stacks.
Stacks.
Stack and Queue APURBO DATTA.
Stacks Stack: restricted variant of list
Stacks.
Stack.
Lists, Stacks and Queues
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks and Queues. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor.
Presentation transcript:

Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix

Stack Overview Stack ADT Basic operations of stack push, pop, top, isEmpty etc. Implementations of stacks using Array Linked list Application to arithmetic expression evaluation

Stack ADT A stack is a list in which insertion and deletion take place at the same end This end is called top The other end is called bottom Stacks are known as LIFO (Last In, First Out) lists. The last element inserted will be the first to be retrieved

Push and Pop Primary operations: Push and Pop Push Add an element to the top of the stack Pop Remove the element at the top of the stack top empty stack A top push an element top push another A B top pop A

Stack class Attributes of Stack n maxTop: the max size of stack n top: the index of the top element of stack n values: point to an array which stores elements of stack Operations of Stack n IsEmpty: return true if stack is empty, return false otherwise n IsFull: return true if stack is full, return false otherwise n Top: return the element at the top of stack n Push: add an element to the top of stack n Pop: delete the element at the top of stack n DisplayStack: print all the data in the stack

Implementation of Stacks Any list implementation could be used to implement a stack n arrays (static: the size of stack is given initially) n Linked lists (dynamic: never becomes full) We will explore implementations based on array

Stack class class Stack { public: Stack(int size = 10);// constructor ~Stack() { delete [] values; // destructor bool IsEmpty() { return top == -1; } bool IsFull() { return top == maxTop; } double Top(); // examine, without popping void Push(const double x); double Pop(); void DisplayStack(); private: int maxTop;// max stack size = size - 1 int top;// current top of stack double* values;// element array };

Create Stack The constructor of Stack Allocate a stack array of size. Initially top is set to -1. It means the stack is empty. When the stack is full, top will have its maximum value, i.e. size – 1. Stack::Stack(int size) { values=new double[size]; top=-1; maxTop=size - 1; } Although the constructor dynamically allocates the stack array, the stack is still static. The size is fixed after the initialization.

Push Stack void Push(const double x); Push an element onto the stack Note top always represents the index of the top element. After pushing an element, increment top. void Stack::Push(const double x) { if (IsFull()) // if stack is full, print error cout << "Error: the stack is full." << endl; else values[++top]=x; }

Pop Stack double Pop() Pop and return the element at the top of the stack Don’t forgot to decrement top double Stack::Pop() { if (IsEmpty()) { //if stack is empty, print error cout << "Error: the stack is empty." << endl; return -1; } else { return values[top--]; }

Stack Top double Top() Return the top element of the stack Unlike Pop, this function does not remove the top element double Stack::Top() { if (IsEmpty()) { cout << "Error: the stack is empty." << endl; return -1; } else return values[top]; }

Printing all the elements void DisplayStack() Print all the elements void Stack::DisplayStack() { cout "; for (int i = top; i >= 0; i--) cout << "\t|\t" << values[i] << "\t|" << endl; cout << "\t| |" << endl; }

Using Stack int main(void) { Stack stack(5); stack.Push(5.0); stack.Push(6.5); stack.Push(-3.0); stack.Push(-8.0); stack.DisplayStack(); cout << "Top: " << stack.Top() << endl; stack.Pop(); cout << "Top: " << stack.Top() << endl; while (!stack.IsEmpty()) stack.Pop(); stack.DisplayStack(); return 0; } result A simple test program

Application 1: Balancing Symbols To check that every right brace, bracket, and parentheses must correspond to its left counterpart e.g. [( )]{ } is legal, but {[( ] )} is illegal Algorithm (1) Make an empty stack. (2) Read characters until end of file i. If the character is an opening symbol, push it onto the stack ii. If it is a closing symbol, then if the stack is empty, report an error iii. Otherwise, pop the stack. If the symbol popped is not the corresponding opening symbol, then report an error (3) At end of file, if the stack is not empty, report an error

Application 2: Expression evaluation Given an arithmetic expression such as: x + y * (z + w) (Given values assigned to x = 23, y = 12, z = 3 and w = -4) What is the value of the expression? Goal: Design a program that takes as input an arithmetic expression and evaluates it. This task is an important part of compilers. As part of this evaluation, the program also needs to check if the given expression is correctly formed. Example of bad expressions: ( * (5 – 3) A + B * + C etc.

Postfix expression Instead of writing the expression as A + B, we write the two operands, then the operator. Example: a b c + * It represents a*(b + c) Question: What is the postfix form of the expression a+ b*c?

Postfix expression Instead of writing the expression as A + B, we write the two operands, then the operator. Example: a b c + * It represents a*(b + c) Question: What is the postfix form of the expression a+ b*c? Answer: a b c * +

Algorithm for evaluating postfix expression l Use a stack. l Push operands on the stack. l When you see an operator, pop off the top two elements of the stack, apply the operator, push the result back. l At the end, there will be exactly one value left on the stack which is the final result.

Algorithm for evaluating postfix expression l Use a stack. l Push operands on the stack. l When you see an operator, pop off the top two elements of the stack, apply the operator, push the result back. l At the end, there will be exactly one value left on the stack which is the final result. Example: * + top 12 top 12 top

top 36 When the entire expression has been read, the stack will contain a single number which is the value of the expression.

Implementation of exp evaluation token class: class token { private: int op_type; double value; public: token(int x, int y) { op_type = x; op_value = y; } int get_op_type() { return op_type; } double get_value() { return value; } void set_op_type(int x) { op_type = x; } void set_value(double y) {value = y; } }; Op_type: 1  + 2  - 3  * 4  / 5  ** 6  operand –1  token represents end of expression op_value: value of the operand.

Main program Look at the main program: int main(void) { string str = " * +/ 123 *"; Expr ex(str, 0); double rslt = ex.eval(); cout << "The result of evaluation is " << rslt << endl; return 0; }; There must be a space between successive operands. There need not be a space when an operand follows an operator, and after an operator. There can be more than one space after any token, including the last.

Expression class Class contains a two data members: l str – a string that represents the expression. l current – an index that represents the current value Member functions: l constructor – creates an expression ex(str, sur) get_token – gets the next token eval – evaluate expression

STL string class Some functions supported by STL string class:

STL string class Some functions supported by STL string class:

Implementation of expression evaluation double eval() { // assumes that the postfix expression is correct // unary minus is not allowed. Operands have to be integers // although the final result need not be an integer Stack st(MAX_SIZE); token tok = get_token(); //gets the next token while (tok.get_op_type() != -1) { if (tok.get_op_type() == 6) st.Push(tok.get_value()); else { double opd2 = st.Pop(); double opd1 = st.Pop(); double op = apply(tok.get_op_type(), opd1, opd2); st.Push(op); } tok = get_token(); } double result = st.Pop(); return result; } // eval

Code for get_token token get_token() { token tok( -1, 0); if (current > exp.length() - 1) return tok; while (exp[current] == ' ') current++; if (current > exp.length() – 1) return tok; if (exp[current] == '+') tok.set_op_type(1); else if (exp[current] == '-') tok.set_op_type(2); else if (exp[current] == '/') tok.set_op_type(4); else if (exp[current] == '*') { if (exp[current+1] != '*') tok.set_op_type(3); else {tok.set_op_type(5); current++;} } else { // token is an operand double temp = 0.0; while (!(exp[current] == ' ') && !optr(exp[current])) { temp= 10*temp+val(exp[current]); current++; } if (optr(exp[current])) current--; tok.set_op_type(6); tok.set_value(temp); } return tok; } //end get_token