Top of the Stack. Stack ADT

Similar documents
Top of the Stack. Stack ADT

All the above operations should be preferably implemented in O(1) time. End of the Queue. Front of the Queue. End Enqueue

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

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

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

Stacks. Revised based on textbook author s notes.

Lecture Data Structure Stack

Stack and Its Implementation

Lecture No.04. Data Structures

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

1. Stack Implementation Using 1D Array

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

STACKS AND QUEUES. Problem Solving with Computers-II

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

1 import java.util.*; 2 3 // implementing hash tables as an array of linked lists 4 // and using it to check whether two sequencs are permutations of

[2:3] Linked Lists, Stacks, Queues

Stacks Fall 2018 Margaret Reid-Miller

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

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

Stack Abstract Data Type

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

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

1 import java.util.*; 2 3 // implementing hash table as an array of linked lists 4 // and using it to print the unique elements of an array 5 6 class

PA3 Design Specification

Abstract Data Types 1

CS350: Data Structures Stacks

infix expressions (review)

09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

CIS Fall Data Structures Midterm exam 10/16/2012

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

Stacks and their Applications

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.

1 import java.util.*; 2 3 // implementing hash table as an array of linked lists 4 // and constructing a union of two linked lists 5 // the union

March 13/2003 Jayakanth Srinivasan,

Stacks, Queues (cont d)

Project 1: Implementation of the Stack ADT and Its Application

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi

CMPS 390 Data Structures

Lab 7 1 Due Thu., 6 Apr. 2017

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

Linear Data Structure

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

List, Stack, and Queues

Lecture 12 ADTs and Stacks

Queues Fall 2018 Margaret Reid-Miller

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

Data Structures And Algorithms

12 Abstract Data Types

CS 211 Programming Practicum Fall 2018

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

An Introduction to Trees

Abstract Data Types 1

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

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

The Stack and Queue Types

CSCI 200 Lab 4 Evaluating infix arithmetic expressions

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

DEEPIKA KAMBOJ UNIT 2. What is Stack?

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

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004)

CS 211 Programming Practicum Spring 2018

CS 211 Programming Practicum Spring 2017

Solution: The examples of stack application are reverse a string, post fix evaluation, infix to postfix conversion.

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

Types of Data Structures

Associate Professor Dr. Raed Ibraheem Hamed

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

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

The Bucharest University of Economic Studies. Data Structures. ADTs-Abstract Data Types Stacks and Queues

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

BBM 201 DATA STRUCTURES

DHANALAKSHMI COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES

DATA STRUCUTRES. A data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.

CS 216 Exam 1 Fall SOLUTION

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 165] Postfix Expressions

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

Module 6: Binary Trees

Stacks. Access to other items in the stack is not allowed A LIFO (Last In First Out) data structure

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

DNHI Homework 3 Solutions List, Stacs and Queues

Dynamic Data Structures

Stacks, Queues and Hierarchical Collections

1 #include <iostream> 2 #include <string> 3 #include <cstring> 4 #include <stdlib.h> //srand, rand 5 #include <time.h>//clock_t, clock,

C Data Structures Stacks. Stack. push Adds a new node to the top of the stack

Lists are great, but. Stacks 2

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

1 #include <iostream> 2 #include <stdlib.h> //srand, rand 3 #include <time.h>//clock_t, clock, CLOCKS_PER_SEC 4 using namespace std; 5 6 //

Stacks. Manolis Koubarakis. Data Structures and Programming Techniques

Programming, Data Structures and Algorithms Prof. Hema Murthy Department of Computer Science and Engineering Indian Institute of Technology, Madras

CSE 230 Intermediate Programming in C and C++

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

Linked List. April 2, 2007 Programming and Data Structure 1

CSC 273 Data Structures

IT 4043 Data Structures and Algorithms. Budditha Hettige Department of Computer Science

Stacks. Ordered list with property: Insertions and deletions always occur at the same end. INSERT DELETE A3 A3 TOP TOP TOP

Stacks II. Adventures in Notation. stacks2 1

Solution for Data Structure

Basic Data Structures

Lecture Notes CPSC 122 (Fall 2014) Today Quiz 7 Doubly Linked Lists (Unsorted) List ADT Assignments Program 8 and Reading 6 out S.

Transcription:

Module 3: Stack ADT Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu

Stack ADT Features (Logical View) A List that operates in a Last In First Out (LIFO) fashion Insertion and deletion can be performed only from one end (i.e., the top of the stack) The last added item has to be removed first Operations: Push( ) adding an item to the top of the stack Pop( ) delete the item from the top of Peek( ) read the item in the top of the stack IsEmpty( ) whether there is any element in the top of the stack All the above operations should be preferably implemented in O(1) time. 6 5 4 3 2 1 0 Push 5 4 3 2 1 0 Top of the Stack Top 6 5 4 3 2 1 0 Pop

Dynamic Array-based Implementation of Stack ADT List ADT Member variables int *array int maxsize int endofarray Constructor List(int size) Member functions bool isempty() void resize(int s) void insert(int data) void insertatindex(int insertindex, int data) int read(int index) void modifyelement(int index, int data) void deleteelement(int deleteindex) Stack ADT Member variables int *array int maxsize int topofstack Constructor Stack(int size) Member functions bool isempty() void resize(int s) void push(int data) int peek() int pop()

Code 3.1: Dynamic Array-based Implementation of Stack ADT C++ Java

Code 3.1 (C++): Dynamic Arraybased Implementation of Stack ADT C++

Code 3.1 (Java): Dynamic Arraybased Implementation of Stack ADT

Code 3.1 (C++): Dynamic Arraybased Implementation of Stack ADT

Code 3.1 (Java): Dynamic Arraybased Implementation of Stack ADT

Implementation of Stack Dynamic Array vs. Singly/Doubly Linked List Push Array: O(n) time, due to need for resizing when the stack gets full Singly Linked List: Θ(n) time Doubly Linked List: O(1) time Pop Array: O(1) time Singly Linked List: Θ(n) time Doubly Linked List: O(1) time Peek Array: O(1) time Singly Linked List: Θ(n) time Doubly Linked List: O(1) time A singly linked list-based implementation would be the most time consuming, as we would need to traverse the entire list for every push, pop and peek operation.

Code 3.2: Class Stack (C++) Doubly Linked List-based Implementation of Stack private: Class (C++) Overview int data; * nextptr; * prevptr; public: ( ) void setdata(int) int getdata() void setnextptr(* ) * getnextptr( ) void setprevptr(* ) * getprevptr( )

Code 3.2: Class Stack (Java) Doubly Linked List-based Implementation of Stack Class (Java) Overview private int data; private nextptr; private prevptr; public ( ) public void setdata(int) public int getdata() public void setnextptr() public getnextptr( ) public void setprevptr() public getprevptr( )

Push Operation Scenario 1: There is no node currently in the stack Head Before Push NULL NULL Tail Head After Push 2 1 NULL New NULL 3 6 Tail headptr tailptr headptr newptr tailptr

Push Operation Scenario 2: There is at least one node already in the stack // Before the new node is pushed, the prevptr for the tail node // would be pointing to the last node in the stack and the nextptr // for that last node would be pointing to NULL. headptr lastptr tailptr Head NULL 1 Last NULL Tail Before Push headptr Head NULL 1 lastptr Last 4 5 New 1 tailptr NULL 6 Tail After Push

Code 3.2 (C++) 1 // There is no other node in the Stack (Scenario 1) 3 2 // There is at least one node already in the Stack (Scenario 2) 4 5 6 Whatever be the case, the prevptr for the tail node will point to the newly pushed node

Code 3.2 (Java) 1 // There is no other node in the Stack (Scenario 1) 3 2 // There is at least one node already in the Stack (Scenario 2) 4 5 6 Whatever be the case, the prevptr for the tail node will point to the newly pushed node

Pop Operation Scenario 1: There will be no node in the Stack after the Pop (i.e., there is just one node in the Stack before the Pop) // Before Pop: The Head s nextptr and the Tail s prevptr are both pointing to the only node in the stack. // After Pop: Both the Head s nextptr and the Tail s prevptr are set to NULL Before Pop After Pop Head NULL Last NULL Tail Head 1 NULL NULL 2 Tail headptr lastptr tailptr headptr tailptr

Pop Operation Scenario 2: There will be at least one node in the stack after the Pop operation is executed headptr Before Pop prevptr lastptr tailptr Head NULL 1 Prev Last NULL Tail headptr Head After Pop NULL 1 prevptr Prev 3 4 tailptr NULL Tail

Code 3.2 (C++) // If there is at least one node in the Stack before Pop // If the Stack is empty before pop, return an invalid value // If there is going to be at least one node in the 3 Stack after the pop 4 (Scenario 2) // If there is going to be no node in the Stack after the pop (Scenario 1) 1 2

Code 3.2 (Java) // If there is at least one node in the Stack before Pop // If the Stack is empty before Pop, return an invalid value // If there is going to be at least one node in the 3 Stack after the pop 4 (Scenario 2) // If there is going to be no node in the Stack after the pop (Scenario 1) 1 2

Code 3.2: Peek Operation C++ Java

Code 3.3 (C++): String Processing Example This code reads a string (of possibly more than one Word) from the user and prints a To read more than word (a line) as string new string that has the uppercase characters Initialize a new string as an empty string of the original string as well as reverses the string Getting the character at a specific index To get the uppercase version of a character Reverse the string from its end to its beginning

To read more than word (a line) as string Initialize a new string as an empty string This code reads a string (of possibly more than one Word) from the user and prints a new string that has the uppercase characters of the original string as well as reverses the string Getting the character at a specific index To get the uppercase version of a character Code 3.3 (Java): String Processing Example Note: String objects are not mutable in Java. Hence, we have to create a new String object that is the reverse of the original string. Reverse the string from its end to its beginning

Parentheses Balance By parenthesis, we refer to the following symbols ( ), { }, [ ] The problem is about checking whether corresponding to each opening parenthesis there is a corresponding closing parenthesis in correct order. Examples for balanced parentheses { [ ] ( ( ) ) } [ ( { } ) [ ] ] ( { } [ ( ) ] ) Examples for unbalanced parentheses [ [ ) ] { ( ) [ }

Parentheses Balance (Program Logic) Logic to determine whether the parentheses in an expression are balanced or not. (We could use a Linked List or Dynamic Array-based Stack). Input the expression as a string and read it one character at a time. If the character read is a opening parenthesis, then push it into the stack If the character read is a closing parenthesis, then pop the stack and check if the popped symbol is a matching opening parenthesis. If so, continue. Otherwise, stop and say, parenthesis is not balanced. If the character read does not match with any of the above six symbols, then stop the program and say there is an invalid symbol in the input expression.

Code 3.4 (C++): Parentheses Balancing Note: We will use the implementation of stack using doubly linked list. We will replace all the int in the doubly linked list based stack code to char as appropriate

Code 3.4 (C++): Parentheses Balancing

Code 3.4 (Java): Parentheses Balancing Note: We will use the implementation of stack using doubly linked list. We will replace all the int in the single linked list based stack code to char as appropriate

Code 3.4 (Java): Parentheses Balancing

Example (C++) for String Tokenization (breaking a string into tokens based on delimiters) Code 3.5 // for C-style string processing as character array In this example program, we will count the number of Symbols and the sum of the integers that appear in an input string sample Get a line of words as a string, sample Create a character array of size one more than the length of the string and copy the elements from the string sample to the Character array samplearray Set up a tokenizer for the character Array with, and blank space as Delimiters. The tokenizer will return Tokens as character arrays (strings)

Run the while loop unless the pointer Corresponding to a token (character array) is NULL Generate a string token corresponding to the Character array Code 3.5 (C++) The compare function returns 0 if the two strings are equal Keep track of the number of symbols The stoi function converts a string to the integer representing it. For example, if 13 is the string token, it is now transformed to an integer value Syntax of the strtok function to read the next token in the original string

Example (Java) for String Tokenization (breaking a string into tokens based on delimiters) Code 3.5 // to use the StringTokenizer and Scanner class In this example program, we will count the number of Symbols and the sum of the integers that appear in an input string sample Get a line of words as a string, sample Set up a tokenizer for the character Array with, and blank space as Delimiters. The tokenizer will return Tokens as strings

Run the while loop until there are tokens remaining Retrieve the next token for the Original string sample Code 3.5 (Java) The equals function returns true if the two strings are equal Keep track of the number of symbols The Integer.parseInt function returns the integer embedded inside a string

Order of Operation (Operator Precedence) 1) Parenthesis: ( ), { }, [ ] 2) Exponent: In case of a tie, we evaluate from right to left. Example: 3^2^4 = 3^16 = 43046721 3) Multiplication and Division: Break the tie, by evaluating from left to right. 4) Addition and Subtraction: Break the tie, by evaluating from left to right. Example: 1) 5 + 8 / 4 = 5 + 2 = 7 2) 12 / 6 * 3 = 2 * 3 = 6 3) 4 * 5 / 2 7 + 3 = 20 / 2 7 + 3 = 10 7 + 3 = 3 + 3 = 6 4) 4 * {5 / (2 7) + 3} = 4 * {5 / (-5) + 3} = 4 * {-1 + 3} = 8

Infix, Prefix and Postfix Infix: LeftOperand <Operator> RightOperand Example: 2 + 3 Prefix: <Operator> LeftOperand RightOperand Example: + 2 3 Postfix: LeftOperand RightOperand <Operator> Example: 2 3 + Infix expressions use the order of operation to break the ties. Prefix and Postfix expressions do not require the order of operation. In both prefix and postfix expressions, each operand will be associated only with one operator and hence no need to use rules of operator precedence. For example: consider a + b * c: this expression (infix notation) needs to use operator precedence for evaluation + a * b c is the prefix notation and abc*+ is the postfix notation

Evaluation of Postfix Expression Consider an infix expression: A * B + C * D E If evaluated in infix, the expression needs to be evaluated as follows: (A * B) + (C * D) E { (A * B) + (C * D)} E Converting this to postfix (AB*) + (CD*) E (AB*) (CD*) + E (AB*) (CD*) + E Removing the parenthesis, the final postfix expression is: AB*CD*+E Evaluation Logic: Scan the expression from left to right. If we see an operand in the expression, push it into the stack. If we see an operator, we pop the last two items from the stack, apply the operator on the two popped items (the first popped item will be the right operand and the second popped item will the left operand) and push the result of the operation to the stack. The only item in the stack after reading the entire expression is the value of the expression.

Evaluation of Post-Fix Expression Consider the post-fix expression AB*CD*+E Let A = 2, B = 3, C = 1, D = 5, E = 4 B = 3 A = 2 D = 5 C = 1 A*B = 6 C*D = 5 A*B = 6 E = 4 A*B + C*D = 11 A*B + C*D E = 7 Note: During a scan of a post-fix expression, the left operand of an operator goes first into the stack followed by the right operand. Hence, during a pop, the right operand comes first out of the stack, followed by the left operand

Code 3.6 C++ Code for Postfix Evaluation We will use the integer-based doubly linked list implementation of stack. Check if the token is one of the four operators *, /, +, -; if so, set the isoperator boolean to true If the token is not an operator, we assume It must be an integer, and push it into the Stack.

The right operand is popped first followed by the Left operand If isoperator is true, then pop the top two integers from the Stack, perform the operation and Push the resulting value to the stack Code 3.6 (C++) continued //end if // end while Set up the next iteration of the while loop by retrieving the next token The final value of the expression will be the only value in the stack when we exit the while loop.

Code 3.6 Java Code Retrieve the next token for Postfix Evaluation We will use the integer-based doubly linked list implementation of stack. Check if the token is one of the four operators *, /, +, -; if so, set the isoperator boolean to true If the token is not an operator, we assume it must be an integer, and push it into the Stack.

The right operand is popped first followed by the Left operand If isoperator is true, then pop the top two integers from the Stack, perform the operation and Push the resulting value to the stack Code 3.6 (Java) continued //end if // end while The final value of the expression will be the only value in the stack when we exit the while loop.

Evaluation of Prefix Expression Consider an infix expression: A * B + C * D E If evaluated in infix, the expression needs to be evaluated as follows: (A * B) + (C * D) E { (A * B) + (C * D)} E Converting this to prefix (*AB) + (*CD) E + (*AB) (*CD) E + (*AB) (*CD) E Removing the parenthesis, the final prefix expression is: + *AB*CDE Evaluation Logic: Scan the expression from right to left (or reverse the expression and scan from left to right). If we see an operand in the expression, push it into the stack. If we see an operator, we pop the last two items from the stack, apply the operator on the two popped items (the first popped item will be the left operand and the second popped item will the right operand) and push the result of the operation to the stack. The only item in the stack after reading the entire expression is the value of the expression.

Evaluation of Pre-Fix Expression Consider the pre-fix expression + *AB*CDE Read this expression from right to left Let A = 2, B = 3, C = 1, D = 5, E = 4 C = 1 B = 3 D = 5 E = 4 A = 2 C*D = 5 E = 4 A*B = 6 C*D = 5 E = 4 A*B + C*D = 11 E = 4 A*B + C*D E = 7 Note: During a scan of a pre-fix expression, the right operand of an operator goes first into the stack followed by the left operand. Hence, during a pop, the left operand comes first out of the stack, followed by the right operand