Professional Documents
Culture Documents
A Linear Data Structure: Stack
A Linear Data Structure: Stack
A Linear Data Structure: Stack
BY :- SANTOSH K DEVAL
PGT(Comp.Sc.)
SANTOSH K DEVAL, PGT (CS), KV2,
JAMNAGAR
DATA STRUCTURE:-
Data Structure
Simple Compound
top X X
3
3
Z Push P
2 Z
2
Y 1 Y
1
N 0 N
0
S. K. DEVAL, PGT(CS), KV2, JAMNAGAR
Algorithm for pushing in stack array
/* Assuming that array-stack can hold maximum N elements
1. top = -1
2. Read Item
3. If (top = = N-1)
{
4 Print “ Overflow’
}
5. Else
{
6. top = top +1
7. stack [top] = Item
}
8. End.
S. K. DEVAL, PGT(CS), KV2, JAMNAGAR
POP Operation
4
4
X 3
3
Z Pop once
2 Z
2
Y 1 Y
1
N 0 N
0
S. K. DEVAL, PGT(CS), KV2, JAMNAGAR
Algorithm for popping from stack array
/* Firstly , check for underflow condition N elements
1. If top == -1 then
{
2. Print “ Underflow’
3. Exit from program
}
4. Else
{
5. Print stack(top)
6. top = top -1
}
8. End. S. K. DEVAL, PGT(CS), KV2, JAMNAGAR
Programming Example (Pushing)
int Push (int stack[ ], int & top, int ele ) // function to pop element
{
if (top == size-1)
return (-1);
else
{
top++;
stack[ top] = ele;
}
return 0;
}
S. K. DEVAL, PGT(CS), KV2, JAMNAGAR
Programming Example (Poping)
int Pop (int stack[ ], int & top) // function to pop element
{
int ret;
if (top == -1)
return (-1);
else
{
ret=stack[ top] ;
top--;
}
return ret;
}
S. K. DEVAL, PGT(CS), KV2, JAMNAGAR
Application of Stacks
The stack are basically applied where LIFO (Last in first out)
scheme is required
I Brackets or Parenthesis
II Exponentiation
III Multiplication or Division
IV Addition or subtraction
Take place in the above specific order. The operator with the sam
( e.g, * and /) are evaluated from left to right)
S. K. DEVAL, PGT(CS), KV2, JAMNAGAR
Steps
Determine the actual evaluation order by
inserting braces
Convert the expression in the innermost
braces into postfix notation by putting the
operator after the operands
Repeat step(ii) until entire expression is
converted into postfix notation
A+B + AB AB +
A + (B*C) + A * BC ABC * +
(A+B)/(C-D)
/+AB-CD AB+CD-/
S. K. DEVAL, PGT(CS), KV2, JAMNAGAR
Example – Convert ( A + B) * C / D in to postfix notation .
Solution –
Step I - (( A + B) * C) / D
Step II - = ((AB+)* C) / D
= (AB+C*) / D
= A B+ C * D /
+
B A + B = 3+2 =5
A A
*
C
5
5 C * 5 = 5 * 4 = 20
Evaluate the following expression I postfix form using stack and sho
content of the stack after execution of each operation-