You are on page 1of 8

Chapter 3

The Stack

The Stack
Definitions: residence
Stack: is an ordered collection of items into which new item may be inserted and from which item may be deleted at one end. Stack is sometimes called a last-in, first-out (or LIFO), and also called pushdown list. Stack top: it is a single end of the stack at which items are inserted and deleted. Empty stack: the stack with no item in it. Underflow: the result of an illegal attempt to pop or access an item from an empty stack. Overflow: the result of an illegal attempt to push item into full stack. Example: look at P.78-79.

Stack primitive operation:


operation Push Pop Empty Description add item to the top of stack remove item from the top of stack determine whether or not the stack is empty Return value void Call statement Push (s,i); i = Pop(s); If(empty(s)); Or x=empty(s); i = stacktop(s);

Stack top

Item on the top of stack True if stack empty, false if not determine what the top Item on the top item on the stack without of stack removing it.

pop operation and stacktop are not defined for an empty stack, so we must test the underflow before these tow operations. before push operation we must test the overflow. stacktop operation can be decomposed into pop and push.

Example: in this example we will see how we may use the stack in problem solving. consider a mathematical expression that includes several set of nested parentheses: 7 (( x * (( x + y ) / ( J 3 )) + y ) / ( 4 2.5 ))
8
Fatemah Ba_hareth

Chapter 3

The Stack

Problem: we want to ensure that the parentheses are nested correctly. we want to check that: 1. There are an equal number of right and left parentheses. 2. Every right parenthesis is preceded by a matching left parenthesis. Solving the problem: The nesting depth at a particular point in an expression is the number scopes that have been opened but not yet closed at that point. The parenthesis count at a particular point in an expression is the number of left parenthesis minus the number of right parenthesis. the two condition that must hold if the parenthesis in an expression form an admissible pattern are as follows: 1. The parenthesis count at the end expression is 0. 2. The parenthesis count at each point in expression is nonnegative. valid= true ; s= the empty stack; while (we have not read the entire string) read the next symbol( symb) of the string; if (symb == '(' || symb == '[' || symb == '{' ) push(s,symb); if (symb == ')' || symb == ']' || symb == '}' ) if (empty(s)) valid=false; else{ i=pop(s); if (i is not the matching opener of symb) valid=false; if (!empty(stack)) valid=false; if (valid) printf("%s","the string is valid"); else printf("%s","the string is invalid"); Why we use stack in the solution of this problem ? look at p.84

Representing stack in C:
There are a several ways to represent stack in C: 1. A stack is an ordered collection of items, and C already contain a data type that is an ordered collection of items: the array.

An array cannot be a stack, it can be the home of the stack.

Fatemah Ba_hareth

Chapter 3

The Stack

2. A stack in C can be declare as a structure that containing tow objects: a. Array to hold the elements of the stack. b. An integer to indicate the position of current top in array. #define STACKSIZE 100 struct stack { int top; int items [STACKSIZE]; }; main( ){ Struct stack s; }

Stack elements can be integer, float, character or any other type. A stack can contain objects of different types using C union. The identifier top must always declare as an integer since it's value represent the position within the array items. The condition of empty stack is top=-1. To implement the stack in C we need pop, push and empty functions

Implementing the pop operation:


Pop function performs 3 actions: 1. If stack is empty, print a warning message and halt execution. 2. If not: remove the top element from the stack. 3. Return this element to the caller program. int pop ( struct stack *ps) { if(empty (ps)) { printf("stack underflow"); exit(1); } return(ps -> items[ps ->top--]); } Pop function call: int x; x = pop(&s); The possibility of underflow must be considered in pop operation. ps is already a pointer to a structure of type stack. therefore the address operator "&" is not used in calling empty function. It's better to test the underflow before calling the pop function to avoid halt execution happen by instruction (exit(1);)
10
Fatemah Ba_hareth

Chapter 3

The Stack

Testing for Exceptional Conditions:


In this function we test the underflow and prevent halt execution. void popandtest ( struct stack *ps,int *px, int *pund) { if(empty (ps)) { *pund = TRUE return; }/* enf if */ *pund = FALSE; *px = ps -> items[ps ->top--]; return; }

Implementing the push operation:


Push function steps: 1. make a room for new item x in the stack by increment the top. 2. insert the new item in this room.

The possibility of overflow must be considered in push operation. Overflow condition is top= STACKSIZE-1

void push ( struct stack *ps, int x) { if(ps -> top ==STACKSIZE-1) { printf("stack overflow"); exit(1); } else ps -> items[++(ps ->top)]=x; return; } Push function call: push(&s,x); Pushandtest function: p.93

11

Fatemah Ba_hareth

Chapter 3

The Stack

Implementing the stacktop operation:


It is not a really primitive operation because it is decomposed into two operations: pop and push. int stacktop ( struct stack *ps, int x) { if(empty(ps)) { printf("stack underflow"); exit(1); } else return (ps -> items[ps ->top]); }

12

Fatemah Ba_hareth

Chapter 3

The Stack

Example:infix, postfix and prefix


Infix notation: the operator is between two operands. Prefix notation: the operator is precedes the two operands. Postfix notation: the operator is follows the two operands. Examples: Infix: Prefix: Postfix: A+B +AB AB+

Operators precedence: 1. Exponentiation ($) 2. Multiplication / Division (* , /) 3. Addition / Subtraction (+ ,-) in unparenthesized operators of the same precedence, the order is assumed to be from left to right except the exponentiation ($),the order is assumed to be from right to left. Example: A+B+C order is (A+B)+C A$B$C order is A$(B$C) Postfix does not need parentheses. The order of the operator in postfix expression determine the actual order of the operation in evaluating the expression. Postfix Infix A+(B*C) ABC*+ (A+B)*C AB+C*

Evaluating a Postfix Expression Algorithm:


Algorithm idea: Push operands in stack. When reach operator ,its operand will be the top two elements on the stack. Pop tow operands, perform the operation and push the result on the stack. opndstk= empty stack; while (not end of input) { symb=next input character; if (symb is operand) push(opndstk, symb); else{ opnd2 = pop(opndstk); opnd1 = pop(opndstk); value= result of applying symb to opnd1and opnd2; push(opndstk, value); }/*end else*/ }/*end while*/ return (pop(opndstk));

13

Fatemah Ba_hareth

Chapter 3

The Stack

Example: evaluate the following postfix expression: 623+-382/+*2$3+ Solution: look at p.99

Program to Evaluate a Postfix Expression: (self study)


p.99-p.101

Converting an Expression from Infix to Postfix:


Expirations within innermost parentheses must first be converted to postfix. So that they can then be treated as a single operand. Operands in postfix ordered in the same order that appear in infix Infix: (A+B)*C Postfix: AB+C* The operator that appears earlier in the postfix string is the one that is applied first. In the converting algorithm we will use: prcd(op1,op2) function that return TRUE if op1 has precedence over op2 when op1 appears to the left of op2 in an infix expression without parentheses. return FALSE otherwise. Examples: prcd('+','+')= TRUE and prcd('*','+')= TRUE. prcd('+','*')= FALSE . prcd('$','$')= FALSE (why?)

Convert from infix to postfix algorithm (without parentheses)


opstk=the empty stack; while (not end of input) { symb=next input character; if (symb is operand) add symb to the postfix string else{ while(!empty(opstk) && prcd(stacktop(opstk),symb)) { topsymb=pop(opstk); add topsymb to the postfix string; }/*end while*/ push(opstk,symb); }/*end else*/ }/*end while*/ while(!empty(opstk)) { topsymb=pop(opstk); add topsymb to the postfix string; }/*end while*/

14

Fatemah Ba_hareth

Chapter 3

The Stack

At each point of a simulation an operator on the stack has a lower precedence than all the operators above it, because an operator is pushed onto the stack only if the operator currently on top of the stack has lower precedence than the incoming operator.

Simulate the algorithm with the following infix strings: A*B+C*D A+B*C$D$E What modified if we use parenthesis? 1. When an opening parenthesis read, it must be pushed onto stack. 2. When a closing parenthesis is read, all operators up to the first opening parenthesis must be poped from stack to postfix string. 3. After that opening parenthesis popped off the stack, discarding with closing one ( not add to postfix string). The precedence rules for parenthesis: prcd('(',op)=FALSE for any operator op prcd(op, '(')=FALSE for any operator op other than ')' prcd(op, ')')=TRUE for any operator op other than '(' prcd(')',op)=undefined for any operator op convert from infix to postfix algorithm (with parentheses) same as previous algorithm but we replace the statement push(opstk,symb); with: if (empty(opstk) || symb != ')' ) push(opstk,symb); else topsymb = pop(opstk); Examples: p.104 p.105

Program to Convert an Expression from Infix to Postfix: (self study)


p.107-p.109

15

Fatemah Ba_hareth

You might also like