You are on page 1of 37

Stack

Kashiram pokharel
Stack definition:

• 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. The deletion and insertion in a stack is done from top of the
stack.
• The Insertion operation is referred to as Push and deletion operation is
called POP operation.
• A stack is a container of objects that are inserted and removed according
to the last-in first-out (LIFO) principle. In the pushdown stacks only two
operations are allowed: push the item into the stack, and pop the item out
of the stack.
• A stack is a limited access data structure - elements can be added and
removed from the stack only at the top. Push adds an item to the top of
the stack, pop removes the item from the top Applications of Stack:
Uses:
• Conversion of expression form infix to postfix.
• To evaluate the expressions (postfix, prefix)
• To keep the page-visited history in a Web browser
• To perform the undo sequence in a text editor
• Used in recursion
• To pass the parameters between the functions in a C program
• Can be used as an auxiliary data structure for implementing
algorithms
• Can be used as a component of other data structures
Stack of ADT:-
• Here are the minimal operations we'd need for an abstract stack (and their
typical names):
• Push( S ,x ): Places a value/object x on the Top of the stack S.
• Pop( S): Removes a value/object from the Top of the stack S and
produces that value/ object.
• IsEmpty(S ): Reports whether the stack S is empty or not.
• IsFull( S ): Reports whether the stack S is Full or not (for array
implementation).
• Peak( S ) : produces Top value/object of the stack S without removing it.
• Traverse( S) :visit all elements from Top to Bottom of the stack S without
removing them.
Implementation of stack

• Array implementation of stack (Static Implementation)


• Linked list implementation of array.(Dynamic Implementation)
Array implementation of array:

• This implementation uses a one dimensional array to store the data and top of stack
is an integer value (an index of an array) that indicates the top position of a stack.
• Each time data is added or removed, top is incremented or decremented
accordingly, to keep track of current top of the stack.
• In Array we can push elements one by one from 0th position 1st position ……n-1th
position. Any element can be added or deleted at any place in an array but we can
push or pop the element from the top of the stack only.
• When there is no place for adding the element in the array, then this is called stack
overflow. So first we check the value of top with size of array.
• When there is no element in stack, then value of top will be -1. so we check the
value of top before deleting the element of stack

• Here, Stack is implemented with array, size of stack array is 7 and value of top is 2.
Let Stack[MAX] be an array to implement the stack. The variable top denotes the top
of the stack.
Algorithm for creating a stack

#define MAX 10
struct STACK
{
int stack[MAX]; //Declaring an array to store items
int top; //Top of a stack
};
typedef struct STACK st;
Algorithm for push( )

1. Check for stack overflow condition


if top==MAX-1 then
print “Stack Overflow” and Exit
else
2. increase top by one
Set top=top+1
3. insert value at new top position.
stack[top]=value;
4. End.
Algorithm for pop() using array
1. Check stack underflow condition
If TOP==-1, then
Print: UNDERFLOW, Stack is empty, and End.
2. Assign TOP element to ITEM i.e. set item to be deleted.
Set ITEM = stack[TOP].
3. Decrease TOP by 1
Set TOP=TOP-1.
4. End.
Algorithm for peak( )/top( )

• Here stack is an array with MAX locations. TOP points to the top most
element. This procedure produces the top element of stack and
assigns it to the variable ITEM without removing it.
Algorithm: PEAK( )
1. Check stack underflow condition.
If TOP==-1, then
Print stack UNDERFLOW or Stack is empty, and End.
2. Assign TOP element to ITEM
Set ITEM = stack[TOP]
3. End.
Algorithm for traversing a stack

• Here stack is an array with MAX locations. TOP points to the top most element.
This procedure produces all the values (pushed on stack) without removing them.
• Algorithm: Traverse ( )
1. Check stack underflow condition
If TOP==-1, then
Print: stack UNDERFLOW or Stack is empty, and End.
2. Put TOP into T so that its value not to be changed
T = TOP
3. Repeat While T ≥ 0
Print stack [ T ]
Set T = T –1
4. End.
Mathematical expression:

• An expression is defined as a number of operands or data items combined


using several operators One of the applications of the stack is to evaluate
the expression.
• Symbol used in an expression are:

• We can represent the expression following three types of notation:


• Infix
• Prefix
• Postfix
• Infix, Postfix and Prefix notations are three different but equivalent ways of
writing expressions.
Infix notation: X + Y

• It is most common notation in which, the operator is written or placed in-


between the two operands. For eg. The expression to add two numbers A and B is
written in infix notation as, A + B
• An expression such as A * (B + C ) / D is usually taken to mean something like:
"First add B and C together, then multiply the result by A, then divide by D to give
the final answer."
• Infix notation needs extra information to make the order of evaluation of the
operators clear: rules built into the language about operator precedence and
associativity, and brackets ( ) to allow users to override these rules.
• For example, the usual rules for associativity say that we perform operations from
left to right, so the multiplication by A is assumed to come before the division by
D. Similarly, the usual rules for precedence say that we perform multiplication
and division before we perform addition and subtraction.
Postfix notation (also known as "Reverse Polish
notation"): X Y +
• Operators are written after their operands. The infix expression given
above is equivalent to A B C + * D /
• The order of evaluation of operators is always left-to-right, and brackets
cannot be used to change this order. Because the "+" is to the left of the
"*" in the example above, the addition must be performed before the
multiplication.
Operators act on values immediately to the left of them. For example, the
"+" above uses the "B" and "C". We can add (totally unnecessary) brackets
to make this explicit:
• ( (A (B C +) *) D /)
Thus, the "*" uses the two values immediately preceding: "A", and the
result of the addition. Similarly, the "/" uses the result of the multiplication
and the "D".
Prefix notation (also known as "Polish notation"):
+XY
• Operators are written before their operands. The expressions given above are
equivalent to / * A + B C D
• As for Postfix, operators are evaluated left-to-right and brackets are superfluous.
Operators act on the two nearest values on the right. I have again added (totally
unnecessary) brackets to make this clear:
(/ (* A (+ B C) ) D)
• Although Prefix "operators are evaluated left-to-right", they use values to their
right, and if these values themselves involve computations then this changes the
order that the operators have to be evaluated in.
• In the example above, although the division is the first operator on the left, it acts
on the result of the multiplication, and so the multiplication has to happen before
the division (and similarly the addition has to happen before the multiplication).
The order of evaluation of the operators is not disrupted in the same way as in
Prefix expressions.
Algorithm for infix to post fix conversion.
1. Scan symbol of array infix from left to right.
2. If the symbol is left parenthesis ‘(‘then add in to the stack.
3. If symbol is operand then add it to array post fix.
4. (i) If symbol is operator then repeatedly pop the operator which have same
precedence or higher precedence then the operator which occurred.
(ii) Add those popped operator to array post fix.
(iii) Add the scanned symbol operator in to stack.
5. (i) If symbol is right parenthesis ‘)’ then pop all the operators from stack
until left parenthesis ‘(‘ in stack.
(ii) Remove left parenthesis ‘(‘ from stack.
6. Then pop all the symbol form stack and add them to array post fix except .
7. Do the same process until all character comes in scanning array infix.
Infix to postfix conversion.
Infix to post
Step
fix conversion
Symbol
A*(B+C$D)-E$F*(G/H)
Operator in stack Postfix expression
1 A A
2 * * A
3 ( *( A
4 B *( AB
5 + *(+ AB
6 C *(+ ABC
7 $ *(+$ ABC
8 D *(+$ ABCD
9 ) * ABCD$+
10 - - ABCD$+*
11 E - ABCD$+*E
12 $ -$ ABCD$+*E
13 F -$ ABCD$+*EF
14 * -* ABCD$+*EF$
15 ( -*( ABCD$+*EF$
16 G -*( ABCD$+*EF$G
17 / -*(/ ABCD$+*EF$G
18 H -*(/ ABCD$+*EF$GH
19 ) -* ABCD$+*EF$GH/
20 NULL NULL ABCD$+*EF$GH/*-
Pseudocode:
for (each character character in the infix expression){ case operator: // process stack operators of greater precedence
switch(ch) while (!aStack.isEmpty() and top of stack is not '(' and precedence(ch) <=
{ precedence(top of aStack))
case operand: // append operand to end of PE {
postfixExp = postfixExp + ch; postfixExp = postfixExp + (top of aStack)
break; aStack.pop()
case '(': // save '(' on stack } // end while
aStack.push(ch) aStack.push(ch) // save new operator
Break; break;
case ')': // pop stack until matching '(' } // end switch
while (top of stack is not '(' ) } // end for
{ // append to postfixExp the operators remaining on the stack
postfixExp = postfixExp + (top of aStack) while(!aStack.isEmpty())
aStack.pop() {
} // end while postfixExp = postfixExp + (top of aStack)
aStack.pop() // remove the '(' aStack.pop()
break; } // end while
Evaluation of postfix expression:
Algorithm:
• Scan the symbol of array post fix one by one from left to right.
• If symbol is operand, push in to stack.
• If symbol is operator, then pop last two element of stack and evaluate it as
[top- 1] operator [top] & push it to stack.
• Do the same process until character comes in scanning.
• Pop the element of stack which will be value of evaluation of post fix
arithmetic expression.
Evaluate the postfix expression: 6 2 3 + - 3 8 2 /+ *
2$3+
Pseudo code:
Opndstk = the empty stack;
/* scan the input string reading one */
/* element at 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(opndstack));
Algorithm for converting infix expression to prefix
1. An algorithm for infix to prefix
2. Scan one character at a time from right to left.
3. Repeat while there is any symbol in an expression
1. If ) push it into stack.
2. If operand, push it into prestring
3. If operator,
1. If stack is empty, push it into stack.
2. If not, repeat till precedence of TOS character>scan character
1. Pop and push into prestring
3. Push current operator into stack.
4. If ‘(‘ is found, pop and push into prestring until matching ‘)” is found and cancel both.
4. Pop and push to prestring until stack is empty.
5. Pop and print from prestring until prestring stack is empty.
6. Stop
Example:
Example

• Infix Expression:
A+(B*C-(D/E^F)*G)*H
• Reverse the infix expression:
H*)G*)F^E/D(-C*B(+A
• Make Every left parenthesis “ ( ” as
right “ ) ” and every right
parenthesis “ ) ” as left “ ( ”
(H * ( G * ( F ^ E / D ) - C * B ) + A)
Convert the infix string C-B+A into prefix string.
Evaluation of prefix string:
• Scan the symbol of array pre-fix one by one from right to left.
• If symbol is operand, read its corresponding value and push in to stack.
• If symbol is operator, then pop last two element of stack and evaluate it as
[top] operator [top-1] & push it to stack.
• Do the same process until character comes in scanning.
• Pop the element of stack which will be value of evaluation of post fix
arithmetic expression.
Convert infix to prefix and evaluate the prefix expression
((A+B)-C)+D
EVALUATION (A=1,B=2,C=3,D=4)
Steps Input Stack prefix
symbol
1 D D s.n symbol val op1 op2 Value valstk
2 + + D (op1<op>op2)
3 ) +) D 1 D 4 - - - 4
4 C +) DC 2 C 3 - - - 4,3
5 - +)- DC 3 B 2 - - - 4,3,2
6 ) +)-) DC
4 A 1 - - - 4,3,2,1
7 B +)-) DCB
8 + +)-)+ DCB 5. + - 1 2 3 4,3,3
9 A +)-)+ DCBA 6 - - 3 3 0 4,0
10 ( +)- DCBA+ 7 + - 0 4 4 4
11 ( DCBA+-+
Prefix expression +-+ABCD
A*(B-C) GIVEN A=3,B=2,C=6 then infix 3*(2-6)result= -12
Symbol Stack Prefix
1 ) ) -
2 C ) C
3 - )- C
4 B )- CB
5 ( CB-
6 * * CB-
7 A * CB-A
8 CB-A*
Prefix expression is *A-BC
EVALUATION: *A-BC *3-26 A=3,B=2,C=6
SYMBOL VALUE OP1 OP2 VALUE STACK
1 C 6 6
2 B 2 6,2
3 - 2 6 -4 -4 ( [top] operator [top-1])
4 A 3 -4,3
5 * 3 -4 -12 -12
VALUE -12
Input Prefix_Stack Stack
Infix to prefix conversion G
+
G
G
(empty)
+
) G +)
) G +))
F GF +))
- GF +))-
• Let have an Infix Expression E GFE +))-
• ( (A+B) * (C+D) / (E-F) ) + G ( GFE- +)
/ GFE- +)/
• Reading Expression from “right to left” ) GFE- +)/)
character by character. D GFE-D +)/)
• We have Input, Prefix_Stack & Stack. + GFE-D +)/)+
• Now converting this expression to C GFE-DC +)/)+
( GFE-DC+ +)/
Prefix
* GFE-DC+ +)/*
) GFE-DC+ +)/*)
B GFE-DC+B +)/*)
+ GFE-DC+B +)/*)+
A GFE-DC+BA +)/*)+
( GFE-DC+BA+ +)/*
( GFE-DC+BA+*/ +
(empty) GFE-DC+BA+*/+ (empty)
Evaluate:

• First I’m assigning values to all operands.


A = 14,B = 12,C = 10,D = 8,E = 6,F = 4,G = 2
Evaluating Infix expression using above values.
( (14+12) * (10+8) / (6-4) ) + 2
( 26 * 18 / 2 ) + 2
( 468 / 2 ) + 2
( 234 ) + 2
=236

- Evaluating prefix expression using above values.


+/*+AB+CD–EFG
+ / * + 14 12 + 10 8 - 6 4 2
Evaluation:
s.n Symbol Value Op1 Op2 Value stack
1 G 2 2
2 F 4 2,4
3 E 6 2,4,6
4 - 6 4 2 2,2
5 D 8 2,2,8
6 C 10 2,2,8.10
7 + 10 8 18 2,2,18
8 B 12 2,2,18,12
9 A 14 2,2,18,12,14
10 + 14 12 26 2,2,18,26
11 * 26 18 468 2,2,468
12 / 468 2 234 2,234
13 + 234 2 236 236
**************************END***************************

You might also like