VTU NOTES QUESTION PAPERS NEWS RESULTS FORUMS THE STACK

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:

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

Data Structures Week #3. Stacks

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

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

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

Vtusolution.in DATA STRUCTURES WITH C. (Common to CSE & ISE) Subject Code: 10CS35 I.A. Marks : 25. Hours/Week : 04 Exam Hours: 03

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

STACKS AND QUEUES. Problem Solving with Computers-II

Infix to Postfix Conversion

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

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Linear Data Structure

Lecture No.04. Data Structures

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 ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

BBM 201 DATA STRUCTURES

BBM 201 DATA STRUCTURES

DEEPIKA KAMBOJ UNIT 2. What is Stack?

CS 211 Programming Practicum Spring 2018

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

CS 211 Programming Practicum Fall 2018

Stacks. Revised based on textbook author s notes.

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

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

Operators & Expressions

Lecture Data Structure Stack

Lecture 8: Simple Calculator Application

Stack and Its Implementation

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi

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

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.

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

CS 211 Programming Practicum Spring 2017

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

Operators and Expressions:

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

March 13/2003 Jayakanth Srinivasan,

Stack Abstract Data Type

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

Types of Data Structures

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305

Stacks. Manolis Koubarakis. Data Structures and Programming Techniques

1. Stack Implementation Using 1D Array

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

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

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

Stacks (Section 2) By: Pramod Parajuli, Department of Computer Science, St. Xavier s College, Nepal.

[CS302-Data Structures] Homework 2: Stacks

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

Data Types and Variables in C language

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

06-Oct-18. Lecture No.05. Infix to Postfix A + B A B (A + B)*(C D ) A B + C D * A B * C D + E/F A B C*D E F/+

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

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

Top of the Stack. Stack ADT

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

Data Structures and Algorithms

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

UNIT-II. Part-2: CENTRAL PROCESSING UNIT

Top of the Stack. Stack ADT

LECTURE 17. Expressions and Assignment

Chapter 4: Basic C Operators

// The next 4 functions return true on success, false on failure

An Introduction to Trees

Content: Learning Objectives

Functions. Systems Programming Concepts

STACKS 3.1 INTRODUCTION 3.2 DEFINITION

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Operators and Expressions

Lecture 12 ADTs and Stacks

Data Structures and Algorithms

Lab 7 1 Due Thu., 6 Apr. 2017

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

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

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

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

1 Lexical Considerations

UNIT 3

Fall, 2015 Prof. Jungkeun Park

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Lexical Considerations

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Lecture 02 C FUNDAMENTALS

CSCI 200 Lab 4 Evaluating infix arithmetic expressions

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

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

The Stack and Queue Types

Adapted By Manik Hosen

Project 3: RPN Calculator

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours

15 FUNCTIONS IN C 15.1 INTRODUCTION

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

Data Structures. 1. Each entry in a linked list is a called a (a)link (b)node (c)data structure (d)none of the above

Stacks, Queues and Hierarchical Collections

Transcription:

Contents: Definition and Examples Representing stacks in C Example: infix, prefix, and postfix Exercises THE STACK Definition and Examples A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted at one end, called the top of the stack. A stack is a dynamic, constantly changing object as the definition of the stack provides for the insertion and deletion of items. It has single end of the stack as top of the stack, where both insertion and deletion of the elements takes place. The last element inserted into the stack is the first element deleted-last in first out list (LIFO). After several insertions and deletions, it is possible to have the same frame again. Primitive Operations When an item is added to a stack, it is pushed onto the stack. When an item is removed, it is popped from the stack. Given a stack s, and an item i, performing the operation push(s,i) adds an item i to the top of stack s. push(s, H); push(s, I); push(s, J); Operation pop(s) removes the top element. That is, if i=pop(s), then the removed element is assigned to i. pop(s); 1

Because of the push operation which adds elements to a stack, a stack is sometimes called a pushdown list. Conceptually, there is no upper limit on the number of items that may be kept in a stack. If a stack contains a single item and the stack is popped, the resulting stack contains no items and is called the empty stack. Push operation is applicable to any stack. Pop operation cannot be applied to the empty stack. If so, underflow happens. A Boolean operation empty(s), returns TRUE if stack is empty. Otherwise FALSE, if stack is not empty Example To check the parentheses in any mathematical expression, are nested correctly, we need to ensure that, There are an equal number of right and left parentheses Every right parentheses is preceded by a matching left parentheses For instance, ((A+B) A+B( )A+B(-C (A+B))-(C+D Each left parentheses opens the scope and right parentheses closes the scope. The nesting depth at a particular point in an expression is the number of scopes that have been opened but not yet closed at that point. The parentheses count at a particular point in an expression is the number of left parentheses minus the number of right parentheses that have been encountered in scanning the expression from its left end up to that particular point. The two conditions that must hold if the parentheses in an expression form an admissible pattern are as follows: The parentheses count at the end of the expression is 0. 2

The parentheses count at each point in the expression is nonnegative. A scope ender must be of the same type as its scope opener. Thus, the following strings are illegal. (A+B], [(A++B], A-(B] The last scope to be opened must be the first to be closed. This is simulated by a stack in which the last element arriving is the first to leave. Representing stacks in C Before programming a problem solution that uses a stack, we must decide how to represent the stack in a programming language. It is an ordered collection of items. In C, we have ARRAY as an ordered collection of items. But a stack and an array are two different things. The number of elements in an array is fixed. A stack is a dynamic object whose size is constantly changing. So, an array can be declared large enough for the maximum size of the stack. A stack in C is declared as a structure containing two objects: An array to hold the elements of the stack. An integer to indicate the position of the current stack top within the array. #define STACKSIZE 100 struct stack int top; int items[stacksize]; ; The stack s may be declared by struct stack s; The stack items may be either int, float, char, etc. The empty stack contains no elements and can therefore be indicated by top= -1. To initialize a stack S to the empty state, we may initially execute s.top= -1. 3

To determine stack empty condition, if (s.top=-1) stack empty; else stack is not empty; The empty(s) may be considered as follows: int empty(struct stack *ps) if(ps->top== -1) return(true); else return(false); Aggregating the set of implementation-dependent trouble spots into small, easily identifiable units is an important method of making a program more understandable and modifiable. This concept is known as modularization, in which individual functions are isolated into low-level modules whose properties are easily verifiable. These low-level modules can then be used by more complex routines, which do not have to concern themselves with the details of the lowlevel modules but only with their function. The complex routines may themselves then be viewed as modules by still higher-level routines that use them independently of their internal details. Implementing pop operation If the stack is empty, print a warning message and halt execution. Remove the top element from the stack. Return this element to the calling program int pop(struct stack *ps) if(empty(ps)) 4

printf( %, stack underflow ); exit(1); return(ps->items[ps->top--]); Testing for exceptional conditions Within the context of a given problem, it may not be necessary to halt execution immediately upon the detection of underflow. Instead, it might be more desirable for the pop routine to signal the calling program that an underflow has occurred. void popandtest(struct stack *ps, int *px, int *pund) if(empty(ps)) *pund=true; return; *pund=false; *px=ps->items[ps->top--]; return; Implementing push operation void push (struct stack *ps, int x ) ps -> items [++(ps->top)] =x; return; Overflow may happen as stack implementation uses an array. So, 5

void push (struct stack *ps, int x) if (ps->top == STACKSIZE-1) printf ( overflow ); exit(1); else ps -> items [++(ps->top)] =x; return; Sometimes, it may not be necessary to halt execution immediately upon the detection of overflow. Instead, the calling program can take corrective action after receiving the overflow signal from push routine - pushandtest(). Example: Infix, postfix and prefix Pre, post and in refer to the relative position of the operator with respect to the two operands. In prefix notation, the operator precedes the two operands. In postfix notation, the operator follows the two operands. In infix notation, the operator is between the two operands. The evaluation of the expression requires knowledge of precedence of operators Highest to lowest Exponentiation ($) Multiplication/division Addition/subtraction The associatively for $ only is assumed to be from right to left Examples Consider the following infix expressions ((A+B)*C-(D-E))$(F+G) A-B/(C*D$E) 6

A$B*C-D+E/F/(G+H) Its corresponding postfix expressions are: AB+C*DE FG+$ ABCDE$*/- AB$C*D-EF/GH+/+ Its corresponding prefix expressions are: $-*+ABC-DE+FG -A/B*C$DE +-*$ABCD//EF+GH The precedence rules for converting an expression from infix to postfix are identical. Remember that, the prefix form of a complex expression is not the mirror image of the postfix form. Both postfix and prefix expressions requires no parentheses. Evaluating a postfix expression Let us now consider an example. Suppose that we are asked to evaluate the following postfix expression: 6 2 3 + - 3 8 2 / + * 2 $ 3 + Symb Opnd1 Opnd2 Value opndstk 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5-6 5 1 1 3 6 5 1 1,3 8 6 5 1 1,3,8 2 6 5 1 1,3,8,2 / 8 2 4 1,3,4 7

+ 3 4 7 1,7 * 1 7 7 7 2 1 7 7 7,2 $ 7 2 49 49 3 7 2 49 49,3 + 49 3 52 52 Each time we read an operand, we push it onto a stack. When we reach an operator, its operands will be the top two elements on the stack. We can then pop these two elements, perform the indicated operation on them, and push the result on the stack so that it will be available for use as an operand of the next operator. The maximum size of the stack is the number of operands that appear in the input expression. But usually, the actual size of the stack needed is less than maximum, as operator pops the top two operands. Program to evaluate postfix expression Along with push, pop, empty operations, we have eval, isdigit and oper operations. eval the evaluation algorithm double eval(char expr[]) int c, position; double opnd1, opnd2, value; struct stack opndstk; opndstk.top=-1; for (position=0 ;( c=expr [position])!= \0 ; position++) if (isdigit) push (&opndstk, (double) (c- 0 )); else opnd2=pop (&opndstk); 8

opnd1=pop (&opndstk); value=oper(c, opnd1,opnd2); push (&opndstk. value); return(pop(&opndstk)); isdigit called by eval, to determine whether or not its argument is an operand int isdigit(char symb) return(symb>= 0 && symb<= 9 ); oper to implement the operation corresponding to an operator symbol double oper(int symb, double op1, double op2) switch (symb) case + : return (op1+op2); case - : return (op1-op2); case * : return (op1*op2); case / : return(op1/op2); case $ : return (pow (op1, op2); default: printf ( %s, illegal operation ); exit(1); Limitations of the program The program does nothing in terms of error detection and recovery. Depending on the specific type of error, the computer may take one of several actions. Suppose that at the final statement of the program, the stack opndstk is not empty. We get no 9

error messages and eval returns a numerical value for an expression that was probably incorrectly stated in the first place. Suppose that one of the calls to the pop routine raises the underflow conditions. Since we did not use the popandtest routine to pop elements from the stack, the program halts. Converting an expression from infix to postfix Consider the given parentheses free infix expression: A + B * C Symb Postfix string opstk 1 A A 2 + A + 3 B AB + 4 * AB + * 5 C ABC + * 6 ABC * + 7 ABC * + Consider the given parentheses infix expression: (A+B)*C Symb Postfix string Opstk 1 ( ( 2 A A ( 3 + A ( + 4 B AB ( + 5 ) AB+ 6 * AB+ * 7 C AB+C * 8 AB+C* 10

Program to convert an expression from infix to postfix Along with pop, push, empty, popandtest, we also make use of additional functions such as, isoperand, prcd, postfix. isoperand returns TRUE if its argument is an operand and FALSE otherwise prcd accepts two operator symbols as arguments and returns TRUE if the first has precedence over the second when it appears to the left of the second in an infix string and FALSE otherwise postfix prints the postfix string Examples exercises 1. Assume A=1, B=2, C=3 Evaluate the following postfix expressions AB+C-BA+C$- ABC+*CBA-+* 2. Transformation or conversion exercises 3. Convert the following infix expression to postfix ((A-(B+C))*D)$(E+F) ***** 11