Stack
Definition-Stack
Stack is a data structure where elements can be added and deleted
from one end only.
Generally, we use top pointer in order to perform this operation.
In other words, we can also say stack to be restricted form of array
where insertion and deletion is possible from one end.
Stack is based on the LIFO.
Stack Implementation
Stack can be implemented by 2 methods-
1. Static implementation using array
Size declaration before execution and it cannot be changed
during execution
2. Dynamic implementation using Linked list
Size declaration during execution and it can be changed.
Operations in Stack
The various primitive operations that are needed for use are
• Initialization of Stack
• Finding if the Stack is Empty
• Insertion or Push
• Deletion or Pop
• Finding Stack Top element or Peek
Stack Initialization
Every stack, before being used, should be initialized. Initialization must
depict that the stack contains zero elements at the beginning. For
example, if we assume the array indexes to vary from 0 to N-1 (N is the
array size), If Top is initialized to 0 index, it means an element is there at
the 0 index. Hence, we should initialize the Top to invalid index, say -1.
ALGORITHM InitializeStack(S)
BEGIN:
Top = – 1
END;
IsEmpty Operation
The function checks the emptiness of the stack. If there is no element in stack then stack is said to
be empty. To check the empty condition, refer to the initialization. If the Top remains at -1, stack is
empty. This is a Boolean value function that either returns true (If the stack is empty) or returns
false (when stack is not empty).
ALGORITHM IsEmpty(S)
BEGIN:
IF (Top == -1)
RETURN TRUE
ELSE
RETURN FALSE
END;
Push Operation
This operation will be used for the insertion of data elements in the
stack. The figure given below shows the insertion process on the stack
ALGORITHM Push (S, item)
Push (S, item)
BEGIN:
• IF Top == MaxSize – 1 THEN
• WRITE(“Stack Overflows”)
• EXIT(1)
• Else
• Top = Top + 1
• Stack[Top] = item
END;
ALGORITHM Push (S, item)
Push (S, item)
Push (S, item) {
BEGIN: if (top == MaxSize – 1)
• IF Top == MaxSize – 1 THEN {
• WRITE(“Stack Overflows”) printf(“Stack Overflows”);
}
• EXIT(1)
else
• Else
{
• Top = Top + 1 top = top + 1;
• Stack[Top] = item Stack[Top] = item;
END; }
}
Push( Top, MAX, DATA, Stack)
Top: Current Position of array
MAX: Maximum length of Array
Item: element to be inserted in stack
Stack: Stack array
Step1: If TOP= MAX-1
Display “stack overflow” and Stop.
Step2: TOP= TOP+1
Step3: READ DATA
Step 4: Stack[TOP]= item
Step 5 : STOP
Pop Operation
This operation will be used for
deletion of a data element from
the stack. Figure given below
shows the deletion process on the
stack.
POP( Top, Stack, ITEM)
Top: Current Position of array
ITEM: item to be deleted
Stack: Stack array
Step1: If TOP==-1 then
Display “stack underflow” and Stop.
Step2: ITEM= Stack[TOP]
Step3: TOP=TOP-1
Step 4: STOP
POP Algorithm
ALGORITHM Pop (S)
BEGIN:
• IF Top == -1 THEN
• WRITE(“Stack Underflows”)
• EXIT(1)
• ELSE
• x =Stack[Top]
• Top = Top – 1
• RETURN x
END;
General Application of Stack
1. Number
Conversion
ALGORITHM: DecimalToBinary (Decimal)
• BEGIN:
• Stack S
• InitializeStack(S)
•
• WHILE Decimal != 0 DO
• r = Decimal % 2
• Push(S, r)
• Decimal = Decimal / 2
•
• WHILE !IsEmpty(S) DO
• x = Pop(S)
• WRITE(x)
END;
2. Reversing of String using
Stack
Another important application of stack is of reversing a string. We can
simply reverse a string using stack. By reversing, we mean that if a
string is "live" then when we read it from last, it will be "evil. "
2. Reversing of String using
Stack
Algorithm StringReverse (Str[])
Begin:
• Stack S
• i=0
• WHILE Str[i] ! = Null DO
• Push(S, str[i])
• i++
•
• WHILE !IsEmpty(S) Do
• x = Pop(S)
• WRITE (x)
End
• Problem: Given a string, use stack to check if this is a Palindrome.
• Problem: Given a Number, use stack to check this is a Palindrome.
3. Balanced Parenthesis
• Parenthesis in the Arithmetic Equations follows the stack property.
Every opening parenthesis must have a corresponding closing
parenthesis. The order of closing of parenthesis are just in the
opposite order of opening of the parenthesis. For example, the
following example can be considered to have balanced parenthesis.
• For example, (a + b) * (c + d) is a valid Expression.
• The expression (a -b)) +((b * 2) is not a valid expression as with
respect to the second “)” closing brace, there does not exist any
opening braces '' (“.
•ALGORITHM ParanthesisCheck(Exp[])
•BEGIN:
• Stack S
• InitializeStack(S)
• Flag = 1 , i = 0
• WHILE Exp[i] == ‘\0’ DO
• IF Exp[i] == ‘(’ THEN
• Push(S, Exp[i])
• ELSE IF Exp[i] == ‘)’ THEN
• IF !Empty(S) THEN
• POP(S)
• ELSE
• Flag = 0
• Break
• i=i+1
•
•IF IsEmpty(S) THEN
• IF Flag == 0 THEN
• WRITE(“Not Balanced”)
• ELSE
• WRITE(“Balanced”)
• ELSE
• WRITE(“Not Balanced”)
•END;
Rules: There is exactly two rules in order to perform this. These are
• Rule 1: - When encountered opening braces ‘(’, simply push onto stack.
• Rule 2: - For every closing brace ')', there should be an opening brace in stack
and we will simply remove one opening braces '(’ from stack. If all expression is
processed if stack is empty and we are not left with any closing braces, then
here expression has equal matching of braces.
Check ()()
Check (())
Check ((())
Check ((())
Check ()())
Check ()())
Infix to Postfix Expression
Notations
Infix : A+B
Prefix: +AB
Postfix : A B+
Precedence Chart
• ()
• !, ++, --, (^ or )
• %
• *, /
• +, -
• Relational operator (< , <=, >, >=)
• ==, !=
• && (logical AND)
• !!(Logical OR)
• = (equal to)
Algorithm to convert infix to postfix
Step 1: Scan the expression from left to right. The symbol is treated as follows.
Step 2: If the symbol is an operand, add the symbol to postfix expression.
Step 3: If the symbol is opening parenthesis “ ( “ , push it on to the stack.
Step 4 :
a. If the symbol is closing parenthesis “)” then repeatedly Pop from the stack
and add each operator to the postfix expression until the corresponding parenthesis
is encountered
b. Remove the opening parenthesis from the stack.
Step 5 :If the symbol is the operator, then check, if the
precedence of the operator at the top of the stack is higher
or same as the current operator , then repeatedly popped
and add it to the postfix expression otherwise it is pushed
into the stack.
Step 6 : Pop the stack until stack is empty. Add the popped element to the postfix
expression.
A+B*C
A+B*C
A+B*C
Symbol scanned Stack Expression P
A A
+ + A
B + AB
* +* AB
C +* ABC
ABC* +
Exampl: A*(B+C)*D
Exampl1: A*(B+C)*D
Symbol scanned Stack Expression P
A A
* * A
( *( A
B *( AB
+ *(+ AB
C *( + ABC
) * ABC+
* * ABC+*
D * ABC+*D
ABC+*D*
((A+B)* D)|^ (E-F)
((A+B)* D) (E-F)
Symbol scanned stack expression
( (
( ((
A (( A
+ ((+ A
B ((+ AB
) ( AB+
* (* AB+
D (* AB+ D
) AB+D*
|^ AB+D*
( ( AB+D*
E AB+D*E
- (- AB+D*E
F AB+D*EF
) AB+D*EF-
Examples
• 1. A+(B*C-(D/E F)*G)*H
• 2. (A-B)/((D+E)*F)
• 3. ((A+B)/D) ((E-F)*G)
• Answer of 1
• ABC*DEF /G*-H*+
Evaluation of Postfix Expression
If stacks are used for evaluation of Prefix and Postfix Expression, Expression
evaluation becomes very simple and straightforward. The precedence and
associativity of operators are not required to be checked while evaluating the
expression using stack.
562+ * 12 4 /-
Scanned symbol stack operation
5 5
6 5,6
2 5,6,2
+ 5,8 A=2,b=6, B0pA =6+2=8
*
12
4
/
-
Answer= 37
Examples: Evaluate the postfix
expression
• Example1 : 2 3 4 + * 5 *
• Example2 : 2 3 1 * + 9 -
• Answers
• exampl1: 70
• Example2 : -4
Evaluation of a postfix expression
using stack
To evaluate the expression, scan the expression from left to right
The steps involved in evaluating a postfix expression are :
Step1: If an operand is encountered push it on stack.
Step2: If an operator “op” is encountered then
a. Pop 2 elements of stack where A is top element and B is the
next top element
b. Evaluate (B op A)
c. Push the result on stack
Step 3: Repeat steps 1 and step 2 until end of expression.
Step 4 : The evaluated value is equal to the value at the top of the stack.
Algorithm to convert infix to prefix
Step 1: Scan the expression from right to left. The symbol is treated as follows.
Step 2: If the symbol is an operand, add the symbol to prefix expression.
Step 3: If the symbol is closing parenthesis “) “ , push it on to the stack.
Step 4 : a. If the symbol is opening parenthesis “(” then repeatedly Pop from the stack
and add each operator to the prefix expression until the corresponding parenthesis is
encountered
b. Remove the closing parenthesis from the stack.
Step 5 :If the symbol is the operator, then check, if the
precedence of the operator at the top of the stack is higher
or same as the current operator , then repeatedly popped
and add it to the postfix expression otherwise it is pushed
into the stack.
Step 6 : Pop the stack until stack is empty. Add the popped element to the prefix
expression.
Step 7 : Finally reverse the expression.
examples
Question 1 : A * B + C / D
answer: + * A B/ C D
Question 2 : (A - B/C) * (A/K-L)
answer : *-A/BC-/AKL