Data Structures Week #3. Stacks

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

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

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

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

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi

VTU NOTES QUESTION PAPERS NEWS RESULTS FORUMS THE STACK

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

The program simply pushes all of the characters of the string into the stack. Then it pops and display until the stack is empty.

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

Outline. Introduction Stack Operations Stack Implementation Implementation of Push and Pop operations Applications. ADT for stacks

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. Manolis Koubarakis. Data Structures and Programming Techniques

BBM 201 DATA STRUCTURES

BBM 201 DATA STRUCTURES

Data Structure - Stack and Queue-

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

Stacks and their Applications

March 13/2003 Jayakanth Srinivasan,

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

Stack and Its Implementation

Stacks. Revised based on textbook author s notes.

CS 211. Project 5 Infix Expression Evaluation

Infix to Postfix Conversion

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

Lecture Data Structure Stack

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

Stack Abstract Data Type

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

Lecture No.04. Data Structures

CS 211 Programming Practicum Spring 2018

CS 211 Programming Practicum Fall 2018

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

An Introduction to Trees

Stacks, Queues (cont d)

Overview of today s lecture. Quick recap of previous C lectures. Introduction to C programming, lecture 2. Abstract data type - Stack example

Prepared by Mrs.D.Maladhy (AP/IT/RGCET) Page 1

Content: Learning Objectives

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

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

Stacks Calculator Application. Alexandra Stefan

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

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

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

CS 211 Programming Practicum Spring 2017

Types of Data Structures

Prepared By:- Dinesh Sharma Asstt. Professor, CSE & IT Deptt. ITM Gurgaon

Stack Applications. Lecture 25 Sections Robb T. Koether. Hampden-Sydney College. Mon, Mar 30, 2015

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

Stacks and Queues. CSE Data Structures April 12, 2002

Data Structures and Algorithms

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

Data Structure. Chapter 3 Stacks and Queues. Department of Communication Engineering National Central University Jhongli, Taiwan.

Lists, Stacks and Queues in C. CHAN Hou Pong, Ken CSCI2100A Data Structures Tutorial 4

Lecture 12 ADTs and Stacks

DEEPIKA KAMBOJ UNIT 2. What is Stack?

STACKS AND QUEUES. Problem Solving with Computers-II

CSE 230 Intermediate Programming in C and C++

DATA STRUCTURE UNIT I

Linear Data Structure

Fall, 2015 Prof. Jungkeun Park

NCS 301 DATA STRUCTURE USING C

Stacks, Queues and Hierarchical Collections

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

[CS302-Data Structures] Homework 2: Stacks

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

STACKS 3.1 INTRODUCTION 3.2 DEFINITION

The Stack and Queue Types

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms...

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

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions

List, Stack, and Queues

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

Stacks. 1 Introduction. 2 The Stack ADT. Prof. Stewart Weiss. CSci 235 Software Design and Analysis II Stacks

Top of the Stack. Stack ADT

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

Stacks. Chapter 3. Exercises. 1. See Figure 3-1. FIGURE 3-1 Solution to Exercise 1

n Data structures that reflect a temporal relationship q order of removal based on order of insertion n We will consider:

Outline. Computer programming. Usage of time and date functions. Date and Time: time.h. Date and Time: time.h. Time functions:

Computer programming. "An expert is a man who has made all the mistakes which can be made, in a narrow field." Niels Bohr

09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

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

Monday, November 13, 2017

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

Application of Stack (Backtracking)

Top of the Stack. Stack ADT

Lab 7 1 Due Thu., 6 Apr. 2017

1. Stack Implementation Using 1D Array

DS Assignment II. Full Sized Image

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

BSc.(Hons.) Business Information Systems, BSc. (Hons.) Computer Science with Network Security, BSc.(Hons.) Software Engineering

Stacks Fall 2018 Margaret Reid-Miller

Chapter 5. ADTs Stack and Queue

15. Stacks and Queues


CSE 214 Computer Science II Stack

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

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS

CSCI 204 Introduction to Computer Science II. Lab 6: Stack ADT

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

Transcription:

Data Structures Week #3 Stacks

Outline Stacks Operations on Stacks Array Implementation of Stacks Linked List Implementation of Stacks Stack Applications October 5, 2015 Borahan Tümer, Ph.D. 2

Stacks (Yığınlar) A stack is a list of data with the restriction that data can be retrieved from or inserted to the top of the list. By top we mean a pointer pointing to the element that is last added to the list. A stack is a last-in-first-out (LIFO) structure. October 5, 2015 Borahan Tümer, Ph.D. 3

Operations on Stacks Two basic operations related to stacks: Push (Put data to the top of the stack) Pop (Retrieve data from the top of the stack) October 5, 2015 Borahan Tümer, Ph.D. 4

Array Implementation of Stacks Stacks can be implemented by arrays. During the execution, the stack can grow by push operations, or shrink by pop operations within this array. One end of the array is the bottom and insertions and deletions (removals) are made from the other end. We also need another field that, at each point, keeps track of the current position of the top of the stack. October 5, 2015 Borahan Tümer, Ph.D. 5

Sample C Implementation #define stacksize ; struct datatype { typedef struct datatype mytype; struct stacktype { int top; mytype items[stacksize]; typedef struct stacktype stacktype; stacktype stack; stack structure October 5, 2015 Borahan Tümer, Ph.D. 6

Sample C Implementation isempty() //Initialize Stack (i.e., set value of top to -1) stack.top=-1; int isempty(stacktype s) { if (s.top == -1) return 1; //meaning true else return 0; //meaning false October 5, 2015 Borahan Tümer, Ph.D. 7

Pop Operation int pop(stacktype *sptr, mytype *node) { if ( isempty(*sptr) ) { printf("stack empty"); return 0; //failure *node = sptr->items[sptr->top]; sptr->top-- ; //or *node = sptr->items[sptr->top--]; return 1; //success October 5, 2015 Borahan Tümer, Ph.D. 8

Sample C Implementation pop() int pop(stacktype *sptr, mytype *node) { if ( isempty(*sptr) ) { printf("stack empty"); return 0; //failure *node = sptr->items[sptr->top--]; return 1; //success October 5, 2015 Borahan Tümer, Ph.D. 9

Push Operation int push(stacktype *sptr, mytype *node, int n){ if ( sptr->top >= n ) { printf("stack full"); return 0; //failure ++(sptr->top); //or sptr->content[++(sptr->top)]=node; sptr->content[ (sptr->top)]=node; return 1; //success October 5, 2015 Borahan Tümer, Ph.D. 10

Sample C Implementation push() int push(stacktype *sptr, mytype *node, int n){ if ( sptr->top >= n ) { printf("stack full"); return 0; //failure sptr->items[++(sptr->top)]=*node; return 1; //success October 5, 2015 Borahan Tümer, Ph.D. 11

Linked List Implementation of Stacks //Declaration of a stack node struct StackNode { int data; struct StackNode *next; typedef struct StackNode StackNode; typedef StackNode * StackNodePtr; October 5, 2015 Borahan Tümer, Ph.D. 12

Linked List Implementation of Stacks StackNodePtr NodePtr, top; NodePtr = malloc(sizeof(stacknode)); top = NodePtr; NodePtr->data=2; // or top->data=2 NodePtr->next=NULL; // or top->next=null; Push(&top,&NodePtr); //Nodeptr is an output variable!!! Pop(&top); October 5, 2015 Borahan Tümer, Ph.D. 13

Push and Pop Functions Void Push (StackNodePtr *TopPtr, StackNodePtr *NewNodePtr) { *NewNodePtr = malloc(sizeof(stacknode)); // NewNodePtr to pass to invoking function!!! (*NewNodePtr)->data=5; (*NewNodePtr)->next = *TopPtr; *TopPtr = *NewNodePtr; Void Pop(StackNodePtr *TopPtr) { StackNodePtr TempPtr; TempPtr= *TopPtr; *TopPtr = *TopPtr->next; free(tempptr); // or you may return TempPtr!!! October 5, 2015 Borahan Tümer, Ph.D. 14

Linked List Implementation of Stacks NodePtr = malloc(sizeof(stacknode)); StackNodePtr *NewNodePtr) { top = NodePtr; NodePtr->data=2; // or top->data=2 Void Push (StackNodePtr *TopPtr, *NewNodePtr = malloc(sizeof(stacknode)); (*NewNodePtr)->data=5; NodePtr->next=NULL;// (*NewNodePtr)->next or top->next=null; Push(&top,&NodePtr); (*NewNodePtr)->next = *TopPtr; *TopPtr = *NewNodePtr; October 5, 2015 Borahan Tümer, Ph.D. 15

Stack Applications Three uses of stacks Symbol matching in compiler design Return address storage in function invocations Evaluation of arithmetic expressions and crossconversion into infix, prefix and postfix versions October 5, 2015 Borahan Tümer, Ph.D. 16

Symbol Matching in Compiler Design Algorithm: 1. Create an empty stack. 2. Read tokens until EOF. Ignore all tokens other than symbols. 3. If token is an opening symbol, push it onto the stack. 4. If token is a closing symbol and stack empty, report an error. 5. Else pop the stack. If symbol popped and opening symbol do not match report an error 6. If EOF and stack not empty, report an error 7. Else, the symbols are balanced. October 5, 2015 Borahan Tümer, Ph.D. 17

Symbol Matching Example: int pop(stack *sptr, mytype *node) { if ( isempty(*sptr) ) { printf("stack empty"); return 0; //failure *node = sptr->items[sptr->top--]; return 1; //success October 5, 2015 Borahan Tümer, Ph.D. 18

Use of Stacks in Function Invocation During a function invocation (function call) Each argument value is copied to a local variable called a dummy variable. Any possible attempt to change the argument changes the dummy variable, not its counterpart in the caller. Memory space is allocated for local and dummy variables of the called function. Control is transferred to the called. Before this, return address of the caller must also be saved. This is the point where a system stack is used. October 5, 2015 Borahan Tümer, Ph.D. 19

Use of Stacks in Function Invocation Returning to the caller, three actions are taken: 1. Return address is retrieved. 2. Data area from the called is cleaned up. 3. Finally, control returns to the caller. Any returned value is also stored in known registers. October 5, 2015 Borahan Tümer, Ph.D. 20

A Function Call Example main( ) { n11 n12 n13 call f2( ); r1 n14 f2( ) { n24 n25 n26 call f3( ); r2 n27 f3( ) { n37 n38 n39 call f4( ); r3 Program Counter n11 n12 n13 n24 n25 n26 n37 n38 n39 n41 n42 n43 r3 r2 n27 r1 n14 r0 Stack Pointer s0 s1 s2 s3 sempty System Stack f4( ) { n41 n42 n43 s3 s2 s1 s0 October 5, 2015 Borahan Tümer, Ph.D. 21

Infix, Postfix and Prefix Formats of Arithmetic Expressions The name of the format of arithmetic expression states the location of the operator. Infix: operator is between the operands (L op R) Postfix: operator is after the operands (L R op) Prefix: operator is before the operands (op L R) October 5, 2015 Borahan Tümer, Ph.D. 22

Examples to Infix, Postfix and Prefix Formats Infix Postfix Prefix A+B AB+ +AB A/(B+C) ABC+/ /A+BC A/B+C AB/C+ +/ABC A-B*C+D/(E+F) ABC*-DEF+/+ +-A*BC/D+EF A*((B+C)/(D-E)+F)-G/(H-I) ABC+DE-/F+*GHI-/- -*A+/+BC-DEF/G-HI October 5, 2015 Borahan Tümer, Ph.D. 23

Rules to watch during Cross-conversions Associative Rules 1) + and - associate left to right 2) * and / associate left to right 3) Exponentiation operator (^ or **) associates from right to left. Priorities and Precedence Rules 1) + and - have the same priority 2) * and / have the same priority 3) (* and /) precede (+ and -) October 5, 2015 Borahan Tümer, Ph.D. 24

Algorithm for Infix Postfix Conversion 1. Initialize an operator stack 2. While not EOArithmeticExpression Do i. Get next token ii. case token of a. ( : Push; //assume the lowest precedence for ( b. ) : Pop and place token in the incomplete postfix expression until a left parenthesis is encountered; If no left parenthesis return with failure c. an operator: a. If empty stack or token has a higher precedence than the top stack element, push token and go to 2.i b. Else pop and place in the incomplete postfix expression and go to c d. an operand: place token in the incomplete postfix expression 3. If EOArithmeticExpression i. Pop and place token in the incomplete postfix expression until stack is empty October 5, 2015 Borahan Tümer, Ph.D. 25

Evaluation of Arithmetic Expressions 1. Initialize an operand stack 2. While not EOArithmeticExpression Do i. Get next token; ii. Case token of a. an operand: push; b. an operator: a. if the last token was an operator, return with failure; b. pop twice; c. evaluate expression; d. push result; October 5, 2015 Borahan Tümer, Ph.D. 26

Evaluation of Arithmetic Expressions Example: 9 8 8 6 - / 2*1+- =? Token Stack Content Operation 9 9 None 8 9 8 None 8 9 8 8 None 6 9 8 8 6 None - 9 8 2 8-6=2 / 9 4 8/2=4 2 9 4 2 none * 9 8 4*2=8 1 9 8 1 None + 9 9 8+1=9-0 9-9 October 5, 2015 Borahan Tümer, Ph.D. 27