+ All Categories
Home > Documents > 71038819

71038819

Date post: 03-Apr-2018
Category:
Upload: jegathis-palaniveloo
View: 214 times
Download: 0 times
Share this document with a friend

of 24

Transcript
  • 7/29/2019 71038819

    1/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 1

    Data Structures using CChapter-3

    STACK AND QUEUE

    STACK Data Structure:

    A stack is an ordered list in which insertions and deletions aremade at one end called the top.

    o If we add the elementsA, B, C, D, Eto the stack, in thatorder, then Eis the first element we delete from the stack

    oA 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 ispushedonto the

    stack.

    pop An item is deleted from the stack i.e. it ispopped

    from the stack.

    Working of stack:

    Stack, which contains max_size number of elements. The element itemis inserted in the stack at the position

    top.

    Initially topis set to 1.

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    2/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 2

    Since the push operation adds elements into a stack, thestack is also called aspushdown list.

    If there are no elements in a stack it is considered asempty stack.

    If the size of the stack is full then it is called stackoverflow.

    Thepush operation is not applicable on full stackotherwise an overflow condition occurs.

    Thepopoperation is not applicable on an empty stackotherwise an underflow condition arises.

    We need to have a new operation empty(s) that checkswhether a stack s is empty or not.

    Another operation on a stack is to determine what the topitem of the stack is without removing it.

    stacktop(s) returns the top element of the stack s.Stack ADT:

    ADT Stack isobjects:

    a finite ordered list with zero or more elements.

    functions:for all stack Stack, item element, max_stack_size

    positive integerStack CreateS(max_stack_size) ::=create an empty stack whose

    maximum size is max_stack_size

    Boolean IsFull(stack, max_stack_size) ::=if(number of elementsin stack == max_stack_size)return TRUEelse return FALSE

    Stack Push(stack, item) ::=if(IsFull(stack))stack_fullelseinsert iteminto top ofstackand returnabstract

    BooleanIsEmpty(stack) ::= if(stack == CreateS(max_stack_size))return TRUEelse return FALSE

    ElementPop(stack) ::= if(IsEmpty(stack)) returnElse remove and return the item on the topof the stack.

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    3/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 3

    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--];}

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    4/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 4

    Stack full:

    void stackFull(){fprintf(stderr, Stack is full, cannot add element);exit(EXIT_FAILRE);}

    Stack Using Dynamic Arrays:

    StackCreateS()::=

    #define MAX_STACK_SIZE 100 /* maximum stack size */typedefstruct{int key;

    /* other fields */} element;element *stack; //declaration of structure variableMALLOC (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;

    }

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    5/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 5

    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 oneend, called the rear and all deletions take place at the oppositeend, called the front

    If we insert the elements A, B, C, D, E, in that order, thenA is the first element we delete from the queue

    A Queue is also known as a First-In-First-Out (FIFO) list

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    6/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 6

    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 positiveintegerQueue 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 TRUEelse return FALSE

    QueueAddQ(queue, item) ::= if(IsFullQ(queue)) queue_fullElse insert item at rear of queue and return queue

    Boolean IsEmptyQ(queue) ::= if(queue==CreateQ(max_queue_size))return TRUEelse returnFALSE

    ElementDeleteQ(queue) ::=if (IsEmptyQ(queue)) returnElse remove and return the item atfront 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 == rearBoolean IsFullQ(queue) ::= rear == MAX_QUEUE_SIZE-1

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    7/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 7

    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;}

    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;}

    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];}

    queueFull(){printf(Queue is Full);return or exit();

    }

    queueFull(){printf(Queue is Full);return or exit();

    }

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    8/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 8

    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 computersolution of many problems.Perhaps the most common occurrence of a queue in computerapplications is for the scheduling of jobs.In batch processing the jobs are ''queued-up'' as they are read-in and executed, one after another in the order they werereceived.This ignores the possible existence of priorities, in which casethere will be one queue for each priority.When we talk of queues we talk about two distinct ends: thefront and the rear.Additions to the queue take place at the rear. Deletions aremade from the front. So, if a job is submitted for execution, itjoins 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 Structurein Operating System:

    creation of job queue- in the operating system which does not use priorities, jobsare processed in the order they enter the system.

    front rear Q[0] Q[1] Q[2] Q[3] Comments-1-1-1-101

    -101222

    J1J1 J2J1 J2 J3* J2 J3* * J3

    queue is emptyjob 1 is addedjob 2 is addedjob 3 is addedjob 1 is deletedjob 2 is deleted

    Note: * representing empty

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    9/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 9

    Problems with normal Queue:

    Queue gradually shifts to the right (as shown above in the jobscheduling queue)

    queue_full(rear==MAX_QUEUE_SIZE-1)Queue_full does not always mean thatthere are MAX_QUEUE_SIZE items inqueuethere may be empty spaces available

    - Solution to save space: Circular queue

    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 counterclockwisefrom the first element in the queue

    - The rear index points to the current end of the queue

    empty queue Non empty Queue

    Note: As the element inthe queue are getting

    filled the rear gettingincremented, but as theelement getting deletedfrom the queue the frontis also incrementingwhere we are wasting lotsof memory without use ofit as shown in the abovefig of job scheduling.

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    10/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 10

    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();}

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    11/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 11

    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 theelements. Let capacity be the number of positions in the arrayqueue. To add an element to a full queue, we must first increasethe size of this array using the function realloc. As withdynamically allocated stacks, we use array doubling.

    However it isnt sufficient to simply double the array size usingrealloc.

    Consider the full queue as shown in fig (a). This figure shows thequeue with seven elements I an array whose capacity is 8. Tovisualize array doubling when a circular queue used, it is betterto flatten out the array as in fig (b).

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    12/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 12

    Fig (c) shows the array after doubling by realloc.To get a proper circular queue configuration, we must slide theelements in the right segment (i.e. element A and B)to the rightend 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 atcapacity-front-1)

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    13/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 13

    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;}

    Add a Circular Queue:

    void addq(element item){/* add an item to the queue */rear = (rear + 1)% capacity;if (front == rear)

    queueFull();queue[rear] = item;

    }

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    14/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 14

    A Mazing Problem:

    The rat-in-a-maze experiment is a classical one from experimentalpsychology.A rat (or mouse) is placed through the door of a large box withouta top.

    Walls are set up so that movements in most directions areobstructed.The rat is carefully observed by several scientists as it makesits way through the maze until it eventually reaches the otherexit.There is only one way out, but at the end is a nice hunk ofcheese.The idea is to run the experiment repeatedly until the rat willzip through the maze without taking a single false path. Thetrials yield his learning curve.

    We can write a computer program for getting through a maze and itwill probably not be any smarter than the rat on its first trythrough. It may take many false paths before finding the rightone. But the computer can remember the correct path far betterthan the rat. On its second try it should be able to go right tothe end with no false paths taken, so there is no sense re-runningthe program. Why don't you sit down and try to write this programyourself before you read on and look at our solution. Keep trackof how many times you have to go back and correct something. Thismay give you an idea of your own learning curve as we re-run theexperiment 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 a0 means one can walk right on through. We assume that the ratstarts at MAZE (1,1) and the exit is at MAZE(m,n).

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    15/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 15

    With the maze represented as a two dimensional array, the locationof 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 possiblemoves 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 surroundingsquares have a 0 then the rat can choose any of these eightsquares as its next position. We call these eight directions bythe 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 themaze by a border of ones.[row][col] which is on border

    - has only three neighbors- surround the maze by a border of 1s

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    16/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 16

    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 thepossible directions to move in a table, MOVE(1:8.1:2), which hasthe values

    Representation in C

    typedef struct{short int vert;short int horiz;} offsets;offsets move[8];/* array of moves for each direction */

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    17/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 17

    If we are at position, maze[row][col], and we wish to find theposition 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 checkedpass 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;

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    18/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 18

    }else++ dir;

    }}if(found)

    {printf(The Path is: );printf(row col);for(i=0; i

  • 7/29/2019 71038819

    19/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 19

    Evaluating postfix expressions is much simpler than theevaluation of infix expressions:

    Before attempting an algorithm to translate expressions frominfix to postfix notation, let us make some observationsregarding the virtues of postfix notation that enable easyevaluation 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 operandsthe correct number from the stack and finally placing the resultonto the stack.This evaluation process is much simpler than attempting a directevaluation from infix notation.

    we make a single left-to-right scanof it.

    an expression easily by using a stack

    Evaluating Postfix Expression:

    6 2/3-4 2*+

    Token Stack[0] [1] [2]

    top

    62/3-42*+

    66 26/26/2 36/2-36/2-3 46/2-3 4 26/2-3 4*26/2-3+4*2

    010101210

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    20/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 20

    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 expressioneval()- if the token is an operand, convert it to number and push tothe stack- otherwise1) pop two operands from the stack2) perform the specified operation3) push the result back on the stack

    function to get a token

    get_token()

    - used to obtain tokens from the expression string

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    21/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 21

    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 elsetoken = get_token(&symbol, &n);} // end of whilereturn 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 */}}

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    22/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 22

    Converging Infix to Postfix

    Different possible algorithms for producing a postfix expressionfrom an infix one

    1) Fully parenthesize the expression

    2) move all binary operators so that they replace theircorresponding right parentheses3) 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 expressionwe will get

    ab/c-de*+ac*-

    This procedure is easy to work only by hand but difficult to bedone using a computer.

    The problem with this as an algorithm is that itrequires two passes:The first one reads the expression and parenthesizes it whilethe second actually moves the operators.As we have already observed, the order of the operands is thesame in infix and postfix.So as we scan an expression for the first time, we can form thepostfix 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 rightmoment 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 Stack[0] [1] [2] top Output

    a+b*ceos

    +++ *+ *

    -10011-1

    aaabababcabc*+

    Translation of a+b*c to postfix

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    23/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCA

    Lecturer: Syed Khutubuddin Ahmed Contact:[email protected] 23

    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 Stack[0] [1] [2]

    top output

    a*(b

    +c)*deos

    ** (* (

    * ( +* ( +****

    -1011

    220000

    aaaab

    ababcabc+abc+*abc+*dabc+*d*

    Translation of a*(b+c)*d to postfix

    Postfix:

    - no parenthesis is needed

    - no precedence is needed

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/29/2019 71038819

    24/24

    SEM-II KNS INSTITUTE OF TECHNLOGY DATA STRUCTURES USING C DEPARTMENT OF MCAFunction 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);}