Vous êtes sur la page 1sur 27

Algorithm & Data Structures CSC112

Fall 2011 lecture 07

Syed Muhammad Raza

Stacks

Type of a data structure used in many applications Based on Last in First out concept (LIFO) data is added and removed at only one end called the top. To add (push) an item to the stack, it must be placed on the top of the stack.

To remove (pop) an item from the stack, it must be removed from the top of the stack too.

Stacks

top top B A C B A top D C B A E D C B A D C B A

top

top

Stacks Applications

Real life

Pile of books Plate trays

More applications related to computer science


Program execution stack Evaluating expressions

Stack Implementation (Array based)

Allocate an array of some size (pre-defined)

Maximum N elements in stack

Bottom stack element stored at element 0 last index in the array is the top Increment top when one element is pushed, decrement after pop

Stack Implementation

Stack createS(max_stack_size) ::= #define MAX_STACK_SIZE 100 /* maximum stack size */ typedef struct { int key; /* other fields */ } element; element stack[MAX_STACK_SIZE]; int top = -1; Boolean isEmpty(Stack) ::= top< 0;

Boolean isFull(Stack) ::= top >= MAX_STACK_SIZE-1;

Push

void push(int *top, element item) { /* add an item to the global stack */ if (*top >= MAX_STACK_SIZE-1) { stack_full( );

return;
} stack[++*top] = item;

Pop

element pop(int *top) { /* return the top element from the stack */ if (*top == -1) return stack_empty( ); /* returns and error key */

return stack[(*top)--];
}

Algorithm Analysis

push pop isEmpty isFull

O(?) O(?) O(?) O(?)

Stack Application

The Towers of Hanoi GIVEN: three poles a set of discs on the first pole, discs of different sizes, the smallest discs at the top GOAL: move all the discs from the left pole to the right one. CONDITIONS: only one disc may be moved at a time. A disc can be placed either on an empty pole or on top of a larger disc.

Stack Application

Balance Symbol Checking

In processing programs and working with computer languages

there are many instances when symbols must be balanced


{},[],() A stack is useful for checking symbol balance. When a closing symbol is found it must match the most recent opening symbol of the same type.

Algorithm for Balanced Symbol Checking


Make an empty stack read symbols until end of file


if the symbol is an opening symbol push it onto the stack if it is a closing symbol do the following

if the stack is empty report an error otherwise pop the stack. If the symbol popped does not match the closing symbol report an error

At the end of the file if the stack is not empty report an error

Example:{x+(y-[a+b])*c-(d+e)}/(h-[j-k])

(
{ {

(
{

{ {x+(y-[a+b]

{ {x+(y-[a+b])

{ {x+(y-[a+b])*c-(

{x+(

{x+(y-[

[
( {x+(y-[a+b])*c-(d+e)} {x+(y-[a+b])*c-(d+e)}/(h-[j-k {x+(y-[a+b])*c-(d+e)}/(h-[j-k])

Infix, Postfix, Prefix


(5+9)*2+6*5
Operand Operator

An ordinary arithmetical expression like the above is called infixexpression -- binary operators appear in between their operands.

The order of operations evaluation is determined by the precedence


rules and parentheses.

When an evaluation order is desired that is different from that provided


by the precedence, parentheses are used to override precedence rules.

Infix, Postfix, Prefix

Expressions can also be represented using postfix notation - where an operator comes after its two operands or prefix notation where an operator comes before its two operands.

The advantage of postfix and prefix notations is that the order of operation evaluation is unique without the need for precedence rules or parentheses.
Infix Notation 16 / 2 (2 + 14)* 5 2 + 14 * 5 (6 2) * (5 + 4) Postfix Notation 16 2 / 2 14 + 5 * 2 14 5 * + 6 2 - 5 4 +* Prefix Notation / 16 2 * + 2 14 5 + * 2 14 5 * - 6 2 + 5 4

Infix to Postfix (Manual)

An Infix to Postfix manual conversion algorithm is:


Completely parenthesize the infix expression according to order of priority you want. Move each operator to its corresponding right parenthesis. Remove all parentheses.

Examples:
3+4*5
(3 + (4 * 5) )

345*+

a/b^cd*ea*c^3^4

abc^/de*ac34^^*--

((a / (b ^ c)) ((d * e) (a * (c ^ (3 ^ 4) ) ) ) )

Infix to Prefix (Manual)

An Infix to Prefix manual conversion algorithm is:

Completely parenthesize the infix expression according to order of priority you want.

Move each operator to its corresponding left parenthesis.


Remove all parentheses.

Examples:

3+4*5

(3 + (4 * 5) )

+3*4 5

a/b^cd*ea*c^3^4

-/a^b c-* d e*a^c^3 4

( (a / (b ^ c)) ( (d * e) (a * (c ^ (3 ^ 4) ) ) ) )

Infix to Postfix Conversion


postfixString = ;

while(infixString has tokens){


Get next token x; if(x is operand) Append x to postfixString; else if(x is ( ) stack.push(x); else if(x is ) ){ y = stack.pop(); while(y is not ( ){ Append y to postfixString; y = stack.pop(); } discard both ( and ); } else if(x is operator){ while(stack is not empty){ y = stack.getTop(); // top value is not removed from stack

if(y is ( ) break;
if(y has low precedence than x) break; if(y is right associative with equal precedence to x) break; y = stack.pop(); Append y to postfixString; } push x;

Infix to Postfix Conversion


while(stack is not empty){ y = stack.pop( ); Append y to postfixString; }

step1:

step2:

step3:

step4:

Infix to Postfix Conversion

step5:

step6:

step7:

step8:

Infix to Postfix Conversion


step9: step10:

step11:

step12:

Infix to Postfix Conversion


step13: step14:

step15:

step16:

Infix to Postfix Conversion step17: step18:

Evaluating Postfix Expression

Each operator in a postfix expression refers to the previous two operands in the expression.

Each time we reach 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 then pop these two elements, perform the indicated operation on them, and push the result on the stack.

In the end, the result of the expression is left as the only element in the stack, which is popped and returned as the result of evaluation

Algorithm for Evaluating a Postfix Expression


opndstk=the empty stack; //scan the input string one element a time into symb while (not end of input) { symb=next input character; if (symb is an operand) push(opndstk, symb); else { //symb is an operator opnd2=pop(opndstk); opnd1=pop(opndstk); value=result of applying symb to opnd1 and opnd2; push(opndstk, value); } //end else } //end while return (pop(opndstk));

Example
6 2 3 + - 3 8 2 / + *
symb opnd1 opnd2 value opndstk

6 2 3 + 3 8 2 2 6 3 5 5 1

2 6,2 6,2,3 6,5 1 1,3 1,3,8 1,3,8,2

/ +
*

8 3
1

2 4
7

4 7
7

1,3,4 1,7
7

Infix to Prefix
An infix to prefix conversion algorithm:

1. Reverse the infix string


2. Perform the infix to postfix algorithm on the reversed string 3. Reverse the output postfix string Example: (A + B) * (B C)
reverse

(C B) * (B + A)
Infix to postfix algorithm

C B - B A + *
reverse

* + A B - B C

Vous aimerez peut-être aussi