Stack ADT
Stack ADT
Stack Model
• A stack is a linear data structure which follows Last In
First Out (LIFO) principle, in which both insertion and
deletion occur at only one end of the list called the Top.
Example
• Pile of coins
• Stack of trays
Operations on Stack
• The fundamental operations performed on a stack are
1. Push
2. Pop
3. Stack Empty
4. Stack Full
PUSH :
return (1);
}
Routine to POP an element from the stack
void pop (Stack S)
{
if (IsEmpty (S))
Error ("Empty Stack");
else
{
X = S [Top];
Top = Top - 1;
}
}
int IsEmpty (Stack S)
{
if (S Top = = -1)
return (1);
}
Routine to return top element of the stack
int TopElement (Stack S)
{
if (! IsEmpty (s))
return S[Top];
else
Error ("Empty Stack");
return 0;
}
LINKED LIST IMPLEMENTATION OF STACK
Struct Node;
typedef Struct Node *Stack;
int IsEmpty (Stack S);
Stack CreateStack (void);
void MakeEmpty (Stack S);
void push (int X, Stack S);
int Top (Stack S);
void pop (Stack S);
Struct Node
{
int Element ;
Struct Node *Next;
};
ROUTINE TO CHECK WHETHER THE STACK IS EMPTY
Stack CreateStack ( )
{
Stack S;
S = malloc (Sizeof (Struct Node));
if (S = = NULL)
Error (" Out of Space");
MakeEmpty (s);
return S;
}
void MakeEmpty (Stack S)
{
if (S = = NULL)
Error (" Create Stack First");
else
while (! IsEmpty (s))
pop (s);
}
ROUTINE TO PUSH AN ELEMENT ONTO A STACK
For example : - A / B + C
POSTFIX
AB / C +
PREFIX
• The arithmetic operator is placed before the two operands
to which it applies. Also called as polish notation. ((A/B) +
C)
• For example : -
+/ABC
INFIX PREFIX (or) POLISH POSTFIX (or) REVERSE POLISH
(A + B) / (C - D) /+AB - CD AB + CD - /
A * B/C + D + / * ABCD AB * C / D +
Evaluating postfix Expression
• Postfix expression is without parenthesis and can be
evaluated as two operands and an operator at a time.
• This becomes easier for the compiler and the computer to
handle.
Evaluation rule of a Postfix Expression states:
• While reading the expression from left to right, push the
element in the stack if it is an operand.
• Pop the two operands from the stack, if the element is an
operator and then evaluate it.
• Push back the result of the evaluation. Repeat it till the
end of the expression.
Evaluating Arithmetic Expression
• To evaluate an arithmetic expressions, first convert the
given infix expression to postfix expression and then
evaluate the postfix expression using stack.
Infix to Postfix Conversion