13
ADT STACK Linear Data Structures Are collections of items arranged in a straight line (i.e. in array, or maybe. . .linked list!) Stacks and Queues are linear data structures, where data can be stored linearly! However: o Some rules are applied when adding and removing items from Stacks and Queues. Stacks A stack is a container where the last item added (pushed) must comes out first (popped) So it is a “Last – in –First – Out”, LIFO The Stack Structure Like any other structure, stacks need to be created, hence the formal operation CREATE Activation of a stack is usually accomplished by initializing the Top pointer to NULL. A stack may grow and then decrease until it is again empty as though freshly activated. The formal operation that checks the validity of a stack is EMPTY A stack grows if a single node is inserted into its Top position. The formal operation that inserts a node into a stack is PUSH The only value of a stack that is accessible to its environment is the value of its Top node. The only reactivable value of a stack is that of its Top node. The formal operation that returns the value of its Top node is TOP The Top node must be removed from a stack before the values of other nodes can be retrieved. The formal operation that removes the Top node from a stack is DELETE Stacks may be implemented by Create, Empty, Insert (Push), Delete and Top, and their interaction. Top followed by Delete implemented as one operation is called POP Characteristics of stacks: A stack can resequence a string of entries A stack is immediate; entry and exits from a stack are first operations. What you get is what you see on top. Data can only be placed on the top of the stack. Data can only be removed from the top of the stack. Data can only be removed from the bottom of the stack if there is only one item on the stack. Data can not be removed from the middle of the stack without first removing all items from the top. 1

Stack Applications June 2012

Embed Size (px)

DESCRIPTION

All is possible in programing of data struct

Citation preview

Page 1: Stack Applications June 2012

ADT STACK Linear Data Structures

Are collections of items arranged in a straight line (i.e. in array, or maybe. . .linked list!) Stacks and Queues are linear data structures, where data can be stored linearly! However:

o Some rules are applied when adding and removing items from Stacks and Queues.

Stacks A stack is a container where the last item added (pushed) must comes out first (popped) So it is a “Last – in –First – Out”, LIFO

The Stack Structure Like any other structure, stacks need to be created, hence the formal operation CREATE Activation of a stack is usually accomplished by initializing the Top pointer to NULL. A stack

may grow and then decrease until it is again empty as though freshly activated. The formal operation that checks the validity of a stack is EMPTY

A stack grows if a single node is inserted into its Top position. The formal operation that inserts a node into a stack is PUSH

The only value of a stack that is accessible to its environment is the value of its Top node. The only reactivable value of a stack is that of its Top node. The formal operation that returns the value of its Top node is TOP

The Top node must be removed from a stack before the values of other nodes can be retrieved. The formal operation that removes the Top node from a stack is DELETE

Stacks may be implemented by Create, Empty, Insert (Push), Delete and Top, and their interaction. Top followed by Delete implemented as one operation is called POP

Characteristics of stacks: A stack can resequence a string of entries A stack is immediate; entry and exits from a stack are first operations. What you get is what you

see on top. Data can only be placed on the top of the stack. Data can only be removed from the top of the stack. Data can only be removed from the bottom of the stack if there is only one item on the stack. Data can not be removed from the middle of the stack without first removing all items from the

top.

ADT Stack Applications Stacks in languages

o Key to call / return in functions and procedureso Stack frame allows recursive callso Call- push stack frame, return – pop stack frameo Stack frame

• Function arguments• Return address• Local variables

Reversing Data: We can use stacks to reverse data. (example: files, strings)o By placing the characters on the stack in the order read, the first character read will be the

last written.o User types: a b c d

Converting Decimal to Binary Evaluating arithmetic expressions.

1

Page 2: Stack Applications June 2012

Stack Behaviors The behavior of putting an item on the stack is called push. The behavior of removing and item from the stack is called pop.

Example What stack exists after executing the following commands?

o push(3)o push(6)o push(8)o push(1)o pop()o pop()o push(14)

Arithmetic Expressions Arithmetic expressions have

o Operands (variables or numeric constants).o Operators

• Binary : +, -, *, / ,%• Unary: -

Priority convention:o - Unary minus (sign for negative numbers) has highest priorityo *, /, % have medium priorityo +, - have lowest priority

Infix, Prefix, Postfix Consider two case studies that relate to evaluating arithmetic expressions

o Postfix and infix notation Expressions normally written in infix form

o Binary operations inserted between their operands A computer normally scans an expression string in the order that it is input; easier to evaluate an

expression in postfix form Example: arithmetic expression a & b consists of operands a, b and operator &.

o Infix notation is format where operator is specified in between the two operands. a&bo Prefix notation is format where operator is specified before the two operands. & a bo Postfix notation is format where operator is specified after the two operands. Postfix

notation is also called RPN or Reverse Polish Notation. a b & Advantage of postfix form is that there is no need to group subexpressions in parentheses No need to consider operator precedence

Arithmetic Expressions

Prefix Notation Infix Notation Postfix Notation

+A * B C A + B * C A B C * +

* + A B C (A+B) * C A B + C *

+ – A B C A – B + C A B – C +

– A + B C A – (B+C) A B C + –

Boolean Expressions

2

Page 3: Stack Applications June 2012

Boolean expressions have o Operands (variables of boolean type or boolean constants TRUE, FALSE).o Operators

• Binary : &, V, =>, ó• Unary: ~

Convention for operator priorities:o ~ has highest priority, o & has next priority level, o v has next priority level,o => has next priority level, o ó has lowest priority.

Infix, Prefix, Postfix for Boolean Expressions Example: Boolean expression a & b consists of operands a, b and operator &.

o Infix notation is format where operator is specified in between the two operands. a&bo Prefix notation is format where operator is specified before the two operands. & a bo Postfix notation is format where operator is specified after the two operands. Postfix

notation is also called RPN or Reverse Polish Notation. a b &

Boolean ExpressionsPrefix Notation Infix Notation Postfix Notationv A & B C A v B & C A B C & v& v A B C (AvB) & C A B v C &v &A B C A & B v C A B & C v& A v B C A & (BvC) A B C v &

Evaluating Arithmetic Expressions in Postfix Notation Algorithm:

o INPUT: list of tokens that are either numbers or binary arithmetic operators +, -,*, /, and %. List represents postfix notation of an arithmetic expression

o OUTPUT: value of expression. To evaluate the postfix expression, it is necessary to:

o Create an empty stack that will contain operands. o Take one by one token from the left to right.

• If token is an operand push it to the stack.• If token is an operator op

– Pop the top item from the stack as operand2.– Pop again the top item from the stack as operand1.– Perform operation operand1 op operand2.– Push result back to stack.

When all tokens in input expression are processed stack should contain a single item, which is the value of expression.

Note:1. An operator in a postfix expression applies to the two operands that immediately precede it. Thus

the operand most recently entered is retrieved first. 2. Each time you enter an operand, the calculator pushes it onto a stack. When you enter an

operator, the calculator applies it to the top two operands from the stack, and then pushes the result of the operation onto the stack.

Pseudo code algorithm that evaluates postfix expressionFor (each character Ch in the string) {

If (Ch is an operand)Push value that operand Ch represents onto a stack

3

Page 4: Stack Applications June 2012

Else //Ch is an operator named Op{ //Evaluate and push the result

Operand1 = top of stackPop the stackOperand2 = top of stackPop the stackResult = Operand1 Op Operand2Push result onto stack

} //end if}//end for

Example 1: Evaluate 5 6 * 10 -

Example 2: Evaluate 3 2 - 4 *

Current Token Stack Content After Processing the Token (Top is at the right side)

What was done

3 3 Push 32 3 2 Push 2- 1 Pop 2 as second operand, pop 3 as first operand,

3-2 is 1. Push 1.4 1 4 Push 4* 4 Pop 4 as second operand, pop 1 as first operand,

1*4 is 4. Push 4.

Exercise:Evaluate the following postfix expressions:1) 1 2 3 + * (Ans 5)2) A * (B + C) When A = 2, B = 3 and C = 4 (Postfix ABC + *) (Ans 14)3) ABC++ when A =1, B = 2, C = 3 (Ans 6)4) A + (B - C)* D When A = 7, B= 3, C = 12, D = -5 (Postfix ABC –D*+) (Ans 52)

Evaluating Boolean Expressions in Postfix Notation Algorithm is same as for arithmetic expressions:

o INPUT: list of tokens that are either TRUE or FALSE or operators &, V, =>, ó. List represents postfix notation of an arithmetic expression.

o OUTPUT: value of expression that is either TRUE or FALSE. Create an empty stack that will contain boolean operands.

4

Page 5: Stack Applications June 2012

o Take one by one token from the left to right.• If token is an operand push it to the stack.• If token is an operator op

– Pop the top item from the stack as operand2.– Pop again the top item from the stack as operand1.– Perform operation operand1 op operand2.– Push result back to stack.

o When all tokens in input expression are processed stack should contain a single item, which is the boolean value of expression.

Evaluate:True True & False =>Current Token Stack Content After

Processing the Token (Top is at the right side)

What was done

True True Push TrueTrue True True Push True& True Pop True as second operand, pop True as first operand,

True&True is true. Push True.False True False Push False=> False Pop False as second operand, pop True as first

operand, True =>False is False. Push False onto stack.

CONVERTING INFIX EXPRESSIONS TO EQUIVALENT POSTFIX EXPRESSIONSThe following are facts about converting from infix to postfix

a) The operands always stay in the same order with respect to one anotherb) An operator will move only to the right with respect to the operands i.e. if, in the infix

expression, the operand X precedes the operator Op, it also true that in the postfix expression, the operand X precedes the operator Op

c) All parentheses are removed

Parentheses, operator precedence and left to right association determine where to place operators in the postfix expression.

Note:1. When assigning precedence, the highest is always exponential function, level two multiplication

and division, level one addition and subtraction2. A further assumption is that operators in the same level of precedence are to be evaluated from

left to right

Algorithm to Convert an Infix Expression to Postfix Accepts: An infix expression

o Convert the expression to POSTFIXo Uses a stack to store operations

Output: The POSTFIX expression

INFIX EXPRESSION TO POSTFIX Initialize an empty stack of operators. While no error has occurred and the end of the infix expression has not been reached, do the

followinga) Get the next input Token (constant, variable, arithmetic operator, left and right parenthesis) in the

infix expression.b) If Token is

i) a left parenthesis: Push it onto the stack

5

Page 6: Stack Applications June 2012

ii) a right parenthesis: Pop and display stack elements until a left parenthesis is popped, but do not display it. (It is an error if the stack becomes empty with no left parenthesis found.)

iii) an operator: If the stack is empty or Token has a higher priority than the top stack, push Token onto the stack. Otherwise, pop and display the top stack element: then repeat the comparison of Token with the new top stack item. A left parenthesis in the stack is assumed to have a lower priority than that of operators. This step orders the operators by precedence and in accordance with left-to-right association.

iv) an operand: Display it.

c) When the end of the infix expression is reached, pop and display stack items until the stack is empty

Example 1: Convert x1 + 2.5 * count /3 to Postfix

o

6

Page 7: Stack Applications June 2012

Example 2: Convert A + B * C - D / E to postfix

Example 3: Convert A * B - ( C + D ) + E to postfix

Example 4: Convert infix expression into postfix (7+1)*(6+ (3-2)) >> POSTFIX

TOKEN Stack After (Top is on the right) Display

( (  

7 ( 7

+ (+ 7

1 (+ 7 1

) 7 1 +

* * 7 1 +

( * ( 7 1 +

6 * ( 7 1 + 6

Infix Stack S(bot->top) Postfixa) A + B * C - D / Eb) + B * C - D / E Ac) B * C - D / E + Ad) * C - D / E + A Be) C - D / E + * A Bf) - D / E + * A B Cg) D / E + - A B C *h) / E + - A B C * Di) E + - / A B C * Dj) + - / A B C * D

Ek) A B C * D E / -

+

Infix Stack(bot->top) Postfix

A * B - ( C - D ) + E empty empty * B - ( C + D ) + E empty A B - ( C + D ) + E * A - ( C + D ) + E * A B - ( C + D ) + E empty A B * ( C + D ) + E - A B * C + D ) + E - ( A B * + D ) + E - ( A B * C D ) + E - ( + A B * C ) + E - ( + A B * C D + E - A B * C D + + E empty A B * C D + - E + A B * C D + - + A B * C D + - E empty A B * C D + - E +

7

Page 8: Stack Applications June 2012

+ * ( + 7 1 + 6

( * ( + ( 7 1 + 6

3 * ( + ( 7 1 + 6 3

- * ( + ( - 7 1 + 6 3

2 * ( + ( - 7 1 + 6 3

) * ( + 7 1 + 6 3 -

) * 7 1 + 6 3 - +

7 1 + 6 3 - + displayedo Stack content *

Add that to displayo 7 1 + 6 3 - + * is POSTFIX

ExerciseConvert the following infix expressions to postfix:a) 7-(2*3+5)*(8-4/2) (Ans 723*5+842/-*- )b) A- ( B + C * D ) / Ec) A + (B * C / D) * E d) B + C * De) A * (B / C / D) + E

Balancing Parentheses in Infix Notation Example

a * ( b + c ) – (( a + b ) / c)) The number of left parentheses must be equal to the number of right parentheses

Checking Parentheses Create an empty stack Until a special symbol appears (indicating the end of expression) do

Read one by one token from the input expressionIf token is{

If the stack is empty push token to the stackIf the stack is non empty pop a top stack elementIf the popped element is ( or [ type an error message such as “Rule 2 is not satisfied at position…” Otherwise push it back and push the token to the stack.[ …( …

} If the stack is empty rule 1 is not satisfied. Type a message …

If the stack is not empty pop the top stack element andIf it is { then read next tokenOtherwise type “Rule 1 is not satisfied at position …

] …) …Other Skip to the next token

8

Page 9: Stack Applications June 2012

If the stack is non empty after the end of expression has been encountered then print an error message such as “Rule 1 is violated at the end of expression”else ”Check control is O.K.”

Summary1. Stack behavior is that of LIFO collection2. Like a list, it is dynamic , increasing with insertion and decreasing with deletion3. Unlike a list, inserted items can only be reached by repeated removal of the top item. A stack

does not require a traversal4. In all its forms, a stack is managed by create, push (insert), delete and top

LAB PROGRAMMING EXERCISE: STACKS

//Stack implementation as a class#include<iostream.h>#include<process.h>#include<conio.h>#define SIZE 20

class stack{int a[SIZE];int tos; // Top of Stack

public:stack();void push(int);int pop();int isempty();int isfull();

};

//Constructorstack::stack(){tos=0; //Initialize Top of Stack}

int stack::isempty(){return (tos==0?1:0);}

int stack::isfull(){return (tos==SIZE?1:0);}

void stack::push(int i){if(!isfull()){a[tos]=i;tos++;}else{cerr<<"Stack overflow error ! Possible Data Loss !";}

}

int stack::pop(){if(!isempty()){

9

Page 10: Stack Applications June 2012

return(a[--tos]);}else{cerr<<"Stack is empty! What to pop...!";}

return 0;}

void main(){stack s;int ch=1,num;

while(ch!=0){cout<<"Stack Operations Main Menu\n1.Push\n2.Pop\n3.IsEmpty\n4.IsFull\n0.Exit\n";cin>>ch;

switch(ch){case 0:

exit(1); //Normal Termination of Program

case 1:cout<<"Enter the number to push"<<endl;;cin>>num;s.push(num);break;

case 2:cout<<"Number popped from the stack is: "<<s.pop()<<endl;break;

case 3:(s.isempty())?(cout<<"Stack is empty."):(cout<<"Stack is not empty.");break;

case 4:(s.isfull())?(cout<<"Stack is full."):(cout<<"Stack is not full.");break;

default:cout<<"Illegal Option.Please try again"<<endl;

}}//end of while

getch();}

10