STACK Data Structure:



Similar documents
Application of Stacks: Postfix Expressions Calculator (cont d.)

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Module 2 Stacks and Queues: Abstract Data Types

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Data Structures Chapter 3 Stacks and Queues

DATA STRUCTURES USING C

DATA STRUCTURE - QUEUE

Common Data Structures

DATA STRUCTURE - STACK

Chapter 3: Restricted Structures Page 1

10CS35: Data Structures Using C

Stacks. Linear data structures

PES Institute of Technology-BSC QUESTION BANK

St S a t ck a ck nd Qu Q eue 1

Data Structures and Algorithms V Otávio Braga

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

7.1 Our Current Model

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Algorithms and Data Structures

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Stack & Queue. Darshan Institute of Engineering & Technology. Explain Array in detail. Row major matrix No of Columns = m = u2 b2 + 1

Data Structure with C

Introduction to Data Structures

Programming with Data Structures

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

Chapter Objectives. Chapter 7. Stacks. Various Types of Stacks LIFO. Empty Stack. Stacks

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Lecture Notes on Linear Search

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Data Structures UNIT III. Model Question Answer

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Analysis of a Search Algorithm

STACKS,QUEUES, AND LINKED LISTS

COMPUTER SCIENCE. Paper 1 (THEORY)

Unit Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

Sources: On the Web: Slides will be available on:

Introduction to Stacks

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

C++ INTERVIEW QUESTIONS

List, Stack and Queue. Tom Chao Zhou CSC2100B Data Structures Tutorial 3

Class Notes CS Creating and Using a Huffman Code. Ref: Weiss, page 433

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Data Structures and Data Manipulation

Stacks. Data Structures and Data Types. Collections

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

Java Interview Questions and Answers

TREE BASIC TERMINOLOGIES

1 Description of The Simpletron

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

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Lecture Notes on Stacks & Queues

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

Partitioning under the hood in MySQL 5.5

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

CmpSci 187: Programming with Data Structures Spring 2015

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Sequential Data Structures

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

What is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation

CS 2412 Data Structures. Chapter 2 Stacks and recursion

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Atmiya Infotech Pvt. Ltd. Data Structure. By Ajay Raiyani. Yogidham, Kalawad Road, Rajkot. Ph : ,

Linear ADTs. Restricted Lists. Stacks, Queues. ES 103: Data Structures and Algorithms 2012 Instructor Dr Atul Gupta

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

Data Structures and Algorithms Stacks and Queues

Introduction to Data Structures and Algorithms

Glossary of Object Oriented Terms

Data Structure [Question Bank]

PROBLEMS (Cap. 4 - Istruzioni macchina)

Basic Data Structures and Algorithms

This Unit: Floating Point Arithmetic. CIS 371 Computer Organization and Design. Readings. Floating Point (FP) Numbers

Queues and Stacks. Atul Prakash Downey: Chapter 15 and 16

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Moving from CS 61A Scheme to CS 61B Java

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

PROGRAMMING CONCEPTS AND EMBEDDED PROGRAMMING IN C, C++ and JAVA: Lesson-4: Data Structures: Stacks

Creating Basic Excel Formulas

Lecture 9. Semantic Analysis Scoping and Symbol Table

CompSci-61B, Data Structures Final Exam

EE2204 DATA STRUCTURES AND ALGORITHM (Common to EEE, EIE & ICE)

Example of a Java program

Chapter 5 Instructor's Manual

Review of Hashing: Integer Keys

Analysis of Micromouse Maze Solving Algorithms

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Transcription:

STACK Data Structure: Data Structures using C Chapter-3 STACK AND QUEUE A stack is an ordered list in which insertions and deletions are made at one end called the top. o If we add the elements A, B, C, D, E to the stack, in that order, then E is the first element we delete from the stack o A stack is also known as a Last-In-First-Out (LIFO) list. Fig: Insert and Delete Elements in the stack Primitive Operations on Stack push An item is added to a stack i.e. it is pushed onto the stack. pop An item is deleted from the stack i.e. it is popped from the stack. Working of stack: Stack, which contains max_size number of elements. The element item is inserted in the stack at the position top. Initially top is set to 1. Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 1

Since the push operation adds elements into a stack, the stack is also called as pushdown list. If there are no elements in a stack it is considered as empty stack. If the size of the stack is full then it is called stack overflow. The push operation is not applicable on full stack otherwise an overflow condition occurs. The pop operation is not applicable on an empty stack otherwise an underflow condition arises. We need to have a new operation empty(s) that checks whether a stack s is empty or not. Another operation on a stack is to determine what the top item of the stack is without removing it. stacktop(s) returns the top element of the stack s. Stack ADT: ADT Stack is objects: a finite ordered list with zero or more elements. functions: for all stack Stack, item element, max_stack_size positive integer Stack CreateS(max_stack_size) ::=create an empty stack whose maximum size is max_stack_size Boolean IsFull(stack, max_stack_size) ::=if(number of elements in stack == max_stack_size) return TRUE else return FALSE Stack Push(stack, item) ::=if(isfull(stack)) stack_fullelseinsert iteminto top of stackand returnabstract BooleanIsEmpty(stack) ::= if(stack == CreateS(max_stack_size)) return TRUE else return FALSE ElementPop(stack) ::= if(isempty(stack)) return Else remove and return the item on the top of the stack. Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 2

Implementation of stack: using array StackCreateS(max_stack_size)::= #define MAX_STACK_SIZE 100 /* maximum stack size */ typedefstruct int key; /* other fields */ element; element stack[max_stack_size]; //declaration of structure variable int top = -1; Boolean IsEmpty(Stack)::= top< 0; Boolean IsFull(Stack) ::= top >= MAX_STACK_SIZE-1; Add and Item to Stack: push() void push(element item) /* add an item to the global stack */ if (top >= MAX_STACK_SIZE-1) stackfull( ); return; stack[++top] = item; Delete an Item to Stack: pop() element pop() /* return the top element from the stack */ if (top == -1) return stackempty( ); /* returns and error key */ return stack[top--]; Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 3

Stack full: void stackfull() fprintf(stderr, Stack is full, cannot add element ); exit(exit_failre); StackCreateS()::= Stack Using Dynamic Arrays: #define MAX_STACK_SIZE 100 /* maximum stack size */ typedefstruct int key; /* other fields */ element; element *stack; //declaration of structure variable MALLOC (stack, sizeof(*stack)); int capacity=1; int top= -1; Boolean IsEmpty(Stack)::= top< 0; Boolean IsFull(Stack) ::= top >= capacity-1; Add and Item to Stack: push() void push(int *top, element item) /* add an item to the global stack */ if (*top >= MAX_STACK_SIZE-1) stackfull( ); return; stack[++*top] = item; Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 4

Delete an Item to Stack: pop() element pop(int *top) /* return the top element from the stack */ if (*top == -1) return stackempty( ); /* returns and error key */ return stack[(*top)--]; Stack full: void stackfull() fprintf(stderr, Stack is full, cannot add element ); exit(exit_failre); Queue Data Structure: A queue is an ordered list in which all insertion take place one end, called the rear and all deletions take place at the opposite end, called the front If we insert the elements A, B, C, D, E, in that order, then A is the first element we delete from the queue A Queue is also known as a First-In-First-Out (FIFO) list Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 5

Queue ADT: Structure Queue is objects: a finite ordered list with zero or more elements. functions: for all queue Queue, item element, max_ queue_ size positive integer Queue CreateQ(max_queue_size) ::= create an empty queue whose maximum size is max_queue_size Boolean IsFullQ(queue, max_queue_size) ::= if(number of elements in queue == max_queue_size) return TRUE else return FALSE QueueAddQ(queue, item) ::= if(isfullq(queue)) queue_full Else insert item at rear of queue and return queue Boolean IsEmptyQ(queue) ::= if(queue==createq(max_queue_size)) return TRUE else returnfalse ElementDeleteQ(queue) ::=if (IsEmptyQ(queue)) return Else remove and return the item at front of queue. Implementation of Queue using Arrays: Queue CreateQ(max_queue_size) ::= #define MAX_QUEUE_SIZE 100/* Maximum queue size */ typedef struct int key; /* other fields */ element; element queue[max_queue_size]; int rear = -1; int front = -1; Boolean IsEmpty(queue) ::= front == rear Boolean IsFullQ(queue) ::= rear == MAX_QUEUE_SIZE-1 Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 6

Add an Element to Queue: void addq(element item) /* add an item to the queue */ if (rear == MAX_QUEUE_SIZE-1) queuefull( ); queue [++rear] = item; queuefull() printf( Queue is Full ); return or exit(); Add an Element to Queue using Pointer: void addq(int *rear, element item) /* add an item to the queue */ if (*rear == MAX_QUEUE_SIZE-1) queuefull( ); return; queue [++*rear] = item; queuefull() printf( Queue is Full ); return or exit(); Delete from a Queue: element deleteq() /* remove element at the front of the queue */ if ( front == rear) return queueempty( ); /* return an error key */ return queue [++front]; Delete from a Queue using Pointer: element deleteq(int*front, intrear) /* remove element at the front of the queue */ if ( *front == rear) return queueempty( ); /* return an error key */ return queue [++ *front]; Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 7

Queue Empty: IsEmptyQ(queue) return (front == rear) Queue Full IsFullQ(queue) return rear == (MAX_QUEUE_SIZE-1) Applications of Queue: Queues, like stacks, also arise quite naturally in the computer solution of many problems. Perhaps the most common occurrence of a queue in computer applications is for the scheduling of jobs. In batch processing the jobs are ''queued-up'' as they are readin and executed, one after another in the order they were received. This ignores the possible existence of priorities, in which case there will be one queue for each priority. When we talk of queues we talk about two distinct ends: the front and the rear. Additions to the queue take place at the rear. Deletions are made from the front. So, if a job is submitted for execution, it joins at the rear of the job queue. The job at the front of the queue is the next one to be executed Solving Job Scheduling Algorithm using Queue data Structure in Operating System: creation of job queue - in the operating system which does not use priorities, jobs are processed in the order they enter the system. front rear Q[0] Q[1] Q[2] Q[3] Comments -1-1 -1 0 J1 queue is empty job 1 is added -1 1 J1 J2 job 2 is added -1 2 J1 J2 J3 job 3 is added 0 2 * J2 J3 job 1 is deleted 1 2 * * J3 job 2 is deleted Note: * representing empty Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 8

Problems with normal Queue: Queue gradually shifts to the right (as shown above in the job scheduling queue) queue_full(rear==max_queue_size-1) Queue_full does not always mean that there are MAX_QUEUE_SIZE items in queue there may be empty spaces available - Solution to save space: Circular queue Note: As the element in the queue are getting filled the rear getting incremented, but as the element getting deleted from the queue the front is also incrementing where we are wasting lots of memory without use of it as shown in the above fig of job scheduling. Circular Queues more efficient queue representation - Representing the array queue[max_queue_size] as circular - Initially front and rear to 0 rather than -1 - The front index always points one position counterclockwise from the first element in the queue - The rear index points to the current end of the queue empty queue Non empty Queue Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 9

Add to Circular Queue: void addq(element item) /* add an item to the queue */ rear = (rear +1) % MAX_QUEUE_SIZE; if (front == rear) /* reset rear and print error */ queuefull( ); queue[rear] = item; queuefull() printf( Queue is Full ); return or exit(); Delete from Circular Queue: element deleteq() element item; /* remove front element from the queue and put it in item */ if (front == rear) return queueempty( ); /* returns an error key */ front = (front+1) % MAX_QUEUE_SIZE; return queue[front]; queuefull() printf( Queue is Empty ); return or exit(); Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 10

Add to Circular Queue using Pointers: void addq(intfront, int*rear, element item) /* add an item to the queue */ *rear = (*rear +1) % MAX_QUEUE_SIZE; if (front == *rear) /* reset rear and print error */ queuefull( ); queue[*rear] = item; Delete from Circular Queue using Pointers: element deleteq(int* front, intrear) element item; /* remove front element from the queue and put it in item */ if (*front == rear) return queueempty( ); /* returns an error key */ *front = (*front+1) % MAX_QUEUE_SIZE; return queue[*front]; queuefull() printf( Queue is Empty ); return or exit(); Circular Queue using dynamically Allocated Arrays Suppose that a dynamically allocated array is used to hold the elements. Let capacity be the number of positions in the array queue. To add an element to a full queue, we must first increase the size of this array using the function realloc. As with dynamically allocated stacks, we use array doubling. However it isn t sufficient to simply double the array size using realloc. Consider the full queue as shown in fig (a). This figure shows the queue with seven elements I an array whose capacity is 8. To visualize array doubling when a circular queue used, it is better to flatten out the array as in fig (b). Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 11

Fig (c) shows the array after doubling by realloc. To get a proper circular queue configuration, we must slide the elements in the right segment (i.e. element A and B)to the right end of the array as in fig (d). To get the configuration as in fig (e) we must follow the following method: 1) Create a new array newqueue of twice the capacity. 2) Copy the second segment (i.e. the elements queue[front + 1] till queue[capacity-1])to positions in newqueue beginning at 0. 3) Copy the first segment (i.e. the elements queue[0] till queue[rear] to position in newqueue beginning at capacity-front-1) Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 12

Code showing Doubling queue capacity: Void queuefull() /* allocate an array with twice the capacity */ element * newqueue; MALLOC(newQueue, 2*capacity*sizeof(*queue)); /* copy from queue to newqueue*/ int start = (front + 1) % capacity; if(start < 2) copy(queue+start, queue+start+capacity-1, newqueue ); else copy(queue+start, queue+capacity, newqueue ); copy(queue, queue+rear+1, newqueue+capacity-start ); /* Switch to newqueue */ front = 2*capacity-1; rear = capacity-2; capacity = capacity * 2; free(queue); queue = newqueue; void addq(element item) /* add an item to the queue */ rear = (rear + 1)% capacity; if (front == rear) queuefull(); queue[rear] = item; Add a Circular Queue: Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 13

A Mazing Problem: The rat-in-a-maze experiment is a classical one from experimental psychology. A rat (or mouse) is placed through the door of a large box without a top. Walls are set up so that movements in most directions are obstructed. The rat is carefully observed by several scientists as it makes its way through the maze until it eventually reaches the other exit. There is only one way out, but at the end is a nice hunk of cheese. The idea is to run the experiment repeatedly until the rat will zip through the maze without taking a single false path. The trials yield his learning curve. We can write a computer program for getting through a maze and it will probably not be any smarter than the rat on its first try through. It may take many false paths before finding the right one. But the computer can remember the correct path far better than the rat. On its second try it should be able to go right to the end with no false paths taken, so there is no sense re-running the program. Why don't you sit down and try to write this program yourself before you read on and look at our solution. Keep track of how many times you have to go back and correct something. This may give you an idea of your own learning curve as we re-run the experiment throughout the book. Experiment implementation: the representation of the maze - Two-dimensional array - Element 0: open path - Element 1: barriers Let us represent the maze by a two dimensional array, MAZE(1:m, 1:n), where a value of 1 implies a blocked path, while a 0 means one can walk right on through. We assume that the rat starts at MAZE (1,1) and the exit is at MAZE(m,n). Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 14

With the maze represented as a two dimensional array, the location of the rat in the maze can at any time be described by the row, i, and column, j of its position. Now let us consider the possible moves the rat can make at some point (i,j) in the maze. Figure 3.6 shows the possible moves from any point (i,j). The position (i,j) is marked by an X. If all the surrounding squares have a 0 then the rat can choose any of these eight squares as its next position. We call these eight directions by the names of the points on a compass north, northeast, east, southeast, south, southwest, west, and northwest, or N, NE, E, SE, S,SW, W, NW. Note: We must be careful here because not every position has eight neighbors. If (i,j) is on a border where either i = 1 or m, or j = 1 or n, then less than eight and possibly only three neighbors exist. To avoid checking for these border conditions we can surround the maze by a border of ones. [row][col] which is on border - has only three neighbors - surround the maze by a border of 1 s Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 15

m * p maze - requires (m + 2) * (p + 2) array - entrance position: [1][1] - exit position: [m][p] Another device which will simplify the problem is to predefine the possible directions to move in a table, MOVE(1:8.1:2), which has the values Representation in C typedef struct short int vert; short int horiz; offsets; offsets move[8];/* array of moves for each direction */ Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 16

If we are at position, maze[row][col], and we wish to find the position of the next move, maze[row][col], we set: next_row = row + move[dir].vert; next_col = col + move[dir].horiz; Initial attempt at a maze traversal algorithm -dimensional array, mark, to record the maze positions already checked pass history #define MAX_STACK_SIZE 100 /*maximum stack size*/ typedef struct short int row; short int col; short int dir; element; element stack[max_stack_size]; Maze Search Algorithm: void path(void) int i, row, col, nextrow, nextcol, dir, found=false; element position; /* structure variable */ mark[1][1]=1; top=0; stack[0].row=1; stack[0].col=1; stack[0].dir=1; while(top > -1 &&!found) position = pop(); row = position.row; col=position.col; dir = position.dir; while(dir < 8 &&!found) /* move in direction dir*/ nextrow = row + move[dir].vert; nextcol = col + move[col].horiz; if(nextrow == EXIT_ROW && nextcol == EXIT_COL) found = TRUE; else if(!maze[nextrow][nextcol] = col &&!mark[nextrow][nextcol]) mark[nextrow][nextcol] = 1; position.row = row; position.col = col; position.dir = ++dir; push(position); row = nextrow; col = nextcol; dir = 0; Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 17

else ++ dir; if(found) printf( The Path is: ); printf( row col ); for(i=0; i<=top; i++) printf( %d%d, stack[i].row, stack[i].col); printf( %d%d, row, col); printf( %d%d, EXIT_ROW, EXIT_COL); else printf( The maze Does not have Path ); Evaluating postfix expressions ssions is known as infix notation binary operator in-between its two operands expressions referred to as postfix -free notation Postfix: - no parentheses, - no precedence Infix 2+3*4 a*b+5 (1+2)*7 a*b/c ((a/(b-c+d))*(e-a)*c a/b-c+d*e-a*c Postfix 2 3 4*+ ab*5+ 1 2+7* ab*c/ abc-d+/ea-*c* ab/c-de*+ac*- Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 18

Evaluating postfix expressions is much simpler than the evaluation of infix expressions: Before attempting an algorithm to translate expressions from infix to postfix notation, let us make some observations regarding the virtues of postfix notation that enable easy evaluation of expressions. To begin with, the need for parentheses is eliminated. Secondly, the priority of the operators is no longer relevant. The expression may be evaluated by making a left to right scan, stacking operands, and evaluating operators using as operands the correct number from the stack and finally placing the result onto the stack. This evaluation process is much simpler than attempting a direct evaluation from infix notation. of it. we make a single left-to-right scan an expression easily by using a stack Evaluating Postfix Expression: 6 2/3-4 2*+ 6 2 / 3-4 2 * + Token Stack [0] [1] [2] 6 6 2 6/2 6/2 3 6/2-3 6/2-3 4 6/2-3 4 2 6/2-3 4*2 6/2-3+4*2 top 0 1 0 1 0 1 2 1 0 Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 19

Representation expression #define MAX_STACK_SIZE 100 /* max stack size */ #define MAX_EXPR_SIZE 100 /* max expression size */ typedef enum lparen, rparen, plus, minus,times, divide, mode, eos, operand precedence; int stack[max_stack_size]; /* global stack */ char expr[max_expr_size]; /* input string */ Function to evaluate a postfix expression eval() - if the token is an operand, convert it to number and push to the stack - otherwise 1) pop two operands from the stack 2) perform the specified operation 3) push the result back on the stack function to get a token get_token() - used to obtain tokens from the expression string Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 20

int eval() precedence token; char symbol; int op1, op2; int n = 0; int top = -1; token = get_token(&symbol, &n); while (token!= eos) if (token == operand) push(&top, symbol- 0 ); else op2 = pop(&top); op1 = pop(&top); switch (token) case plus: push(&top, op1+op2); break; case minus: push(&top, op1-op2); break; case times: push(&top, op1*op2); break; case divide: push(&top, op1/op2); break; case mod: push(&top, op1%op2); // end of else token = get_token(&symbol, &n); // end of while return pop(&top); precedence get_token(char *psymbol, int *pn) *psymbol = expr[(*pn)++]; switch (*psymbol) case ( : return lparen; case ) : return rparen; case + : return plus; case - : return minus; case * : return times; case / : return divide; case % : return mod; case : return eos; default : return operand; /* no error checking */ Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 21

Converging Infix to Postfix Different possible algorithms for producing a postfix expression from an infix one 1) Fully parenthesize the expression 2) move all binary operators so that they replace their corresponding right parentheses 3) Delete all parentheses For eg) a/b-c+d*e-a*c when fully parenthesized it becomes ((((a/b)-c)+(d*e))-a*c)) Perform step-2 and step-3 on the above parenthesized expression we will get ab/c-de*+ac*- This procedure is easy to work only by hand but difficult to be done using a computer. The problem with this as an algorithm is that it requires two passes: The first one reads the expression and parenthesizes it while the second actually moves the operators. As we have already observed, the order of the operands is the same in infix and postfix. So as we scan an expression for the first time, we can form the postfix by immediately passing any operands to the output. Then it is just a matter of handling the operators. The solution is to PUSH them in a stack until just the right moment and then to POP from stack and pass them to the output. 1) Simple expression: Simple expression a+b*c - yields abc*+ in postfix token a + b * c eos Stack [0] [1] [2] + + + * + * top -1 0 0 1 1-1 Output a a ab ab abc abc*+ Translation of a+b*c to postfix Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 22

Parenthesized expression Parentheses make the translation process more difficult - equivalent postfix expression is parenthesis-free expression a*(b+c)*d - yield abc+*d* in postfix right parenthesis - pop operators from a stack until left parenthesis is reached Token a * ( b + c ) * d eos Stack [0] [1] [2] * * ( * ( * ( + * ( + * * * * top -1 0 1 1 2 2 0 0 0 0 output a a a ab ab abc abc+ abc+* abc+*d abc+*d* Translation of a*(b+c)*d to postfix Postfix: - no parenthesis is needed - no precedence is needed Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 23

Function to concert infix to postfix: void postfix(void) char symbol; precedence token; int n = 0; int top = 0; stack[0] = eos; for (token = get_token(&symbol, &n); token!= eos; token = get_token(&symbol, &n)) if (token == operand) printf( %c, symbol); else if (token == rparen) while (stack[top]!= lparen) print_token(pop(&top)); pop(&top); else while (isp[stack[top]] >= icp[token]) print_token(pop(&top)); push(&top, token); while ((token = pop(&top))!= eos) print_token(token); printf( \n ); Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 24