Unit 2 Stack

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

DATA STRUCTURES UNIT-2

Stack
 Stack is an ordered list in which, insertion and deletion can be performed only at one end that is
called top.
 Stack is a recursive data structure having pointer to its top element.
 Stacks are sometimes called as Last-In-First-Out (LIFO) lists i.e. the element which is inserted first in
the stack, will be deleted last from the stack.
Applications of Stack
1. Recursion
2. Expression evaluations and conversions
3. Parsing
4. Browsers
5. Editors
6. Tree Traversals

Operations on Stack
There are various operations which can be performed on stack.

1. Push : Adding an element onto the stack

2. Pop : Removing an element from the stack

3. Peek : Look all the elements of stack without removing them.


How the stack grows?
Scenario 1 : Stack is empty
The stack is called empty if it doesn't contain any element inside it. At this stage, the value of variable top is -
1.

Scenario 2 : Stack is not empty


Value of top will get increased by 1 every time when we add any element to the stack. In the following stack,
After adding first element, top = 2.

Scenario 3 : Deletion of an element


Value of top will get decreased by 1 whenever an element is deleted from the stack.
In the following stack, after deleting 10 from the stack, top = 1.

Top and its value :

Top position Status of stack

-1 Empty

0 Only one element in the stack

N-1 Stack is full

N Overflow

Array implementation of Stack


In array implementation, stack is formed by using the array. All the operations regarding the stack are
performed using arrays.
Adding an element onto the stack (push operation)
Adding an element into the top of the stack is referred to as push operation. Push operation involves following
two steps.
1. Increment the variable Top so that it can now refere to the next memory location.
2. Add element at the position of incremented top. This is referred to as adding new element at the top of
the stack.
Stack is overflow when we try to insert an element into a completely filled stack therefore, our main function
must always avoid stack overflow condition.
Algorithm:
begin
if top = n then stack full
top = top + 1
stack (top) : = item;
end
Time Complexity : O(1)
Deletion of an element from a stack (Pop operation)
Deletion of an element from the top of the stack is called pop operation. The value of the variable top will be
incremented by 1 whenever an item is deleted from the stack. The top most element of the stack is stored in an
another variable and then the top is decremented by 1. the operation returns the deleted value that was stored in
another variable as the result.
The underflow condition occurs when we try to delete an element from an already empty stack.
Algorithm :
begin
if top = 0 then stack empty;
item := stack(top);
top = top - 1;
end;
Time Complexity : O(1)
Visiting each element of the stack (Peek operation)
Peek operation involves returning the element which is present at the top of the stack without deleting it.
Underflow condition can occur if we try to return the top element in an already empty stack.
Algorithm :
PEEK (STACK, TOP)
Begin
if top = -1 then stack empty
item = stack[top]
return item
End
Time complexity: O(n)
Evaluation rule of a Postfix Expression states:
1. While reading the expression from left to right, push the element in the stack if it is an operand.
2. Pop the two operands from the stack, if the element is an operator and then evaluate it.
3. Push back the result of the evaluation. Repeat it till the end of the expression.
Algorithm
1) Add ) to postfix expression.
2) Read postfix expression Left to Right until ) encountered
3) If operand is encountered, push it onto Stack
[End If]
4) If operator is encountered, Pop two elements
i) A -> Top element
ii) B-> Next to Top element
iii) Evaluate B operator A
push B operator A onto Stack
5) Set result = pop
6) END
Let's see an example to better understand the algorithm:
Expression: 456*+

Result: 34
Conversion of Infix to Postfix Expression using Stack
To convert Infix expression to Postfix expression, we will use the stack data structure. By scanning the infix
expression from left to right,if we get any operand, simply add it to the postfix form, and for the operator and
parenthesis, add them in the stack maintaining the precedence of them.
Infix Expression : Infix Expression contains operator in-between every pair of operands,Expression of the
form a op b.
Postfix expression: Postfix Expression contains operator followed for every pair of operands,Expression of
the form a b op.
Why postfix representation of the expression?
 Infix expressions are readable and solvable by humans because of easily distinguishable order of
operators,but compiler doesn't have integrated order of operators.
 Hence to solve the Infix Expression compiler will scan the expression multiple times to solve the
sub-expressions in expressions orderly which is very in-efficient.
 To avoid this traversing, Infix expressions are converted to Postfix expression before evaluation.
Algorithm
 Step 1 : Scan the Infix Expression from left to right.
 Step 2 : If the scanned character is an operand, append it with final Infix to Postfix string.
 Step 3 : Else,
 Step 3.1 : If precedence order of the scanned(incoming) operator is greater than the precedence order of
the operator in the stack (or the stack is empty or the stack contains a ‘(‘ or ‘[‘ or ‘{‘), push it on stack.
 Step 3.2 : Else, Pop all the operators from the stack which are greater than or equal to in precedence
than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you
encounter parenthesis while popping then stop there and push the scanned operator in the stack.)
 Step 4 : If the scanned character is an ‘(‘ or ‘[‘ or ‘{‘, push it to the stack.
 Step 5 : If the scanned character is an ‘)’or ‘]’ or ‘}’, pop the stack and and output it until a ‘(‘ or ‘[‘ or
‘{‘ respectively is encountered, and discard both the parenthesis.
 Step 6 : Repeat steps 2-6 until infix expression is scanned.
 Step 7 : Print the output
 Step 8 : Pop and output from the stack until it is not empty.

Example
Infix Expression : 3+4*5/6
Step 1 : Initially Stack is Empty and first literal of Infix Expression is '3' which is operand hence push in stack.

Stack :
Output : 3

Step 2 : Next literal of expression is + which is operand, hence needed to be pushed on stack but intially stack
is empty hence literal will directly pushed on to stack.

Stack : +
Output : 3
Step 3 : Further 4 is an operand should be pushed on stack.

Stack : +
Output : 3 4

Step 4 : Next literal is * which is an operator, as stack is not empty, priority should be checked of instack
operator(top of stack) and of incoming operator i.e * as priority of instack operator is less than incoming
operator, * will be pushed on to stack.

Stack : + *
Output : 3 4

Step 5 : Next literal is 5 which is an operand, hence should be pushed on to output stack.

Stack : + *
Output : 3 4 5

Step 6 : Next literal is / which is an operator, as stack is not empty, priority should be checked of instack
operator(top of stack) i.e * and of incoming operator i.e /, as priority of / and * are equal hence * will be poped
out of stack and will be stored on output stack and operator / will be stored on stack.

Stack : + /
Output : 3 4 5 *

Step 7 : Next literal is 6 which is an operand, hence should be pushed on output stack.

Stack : + /
Output : 3 4 5 * 6

Step 8 : As now all litrals are traversed, despite stack is not empty, hence pop all litrals from stack and pushed
it on to output stack.
Postfix Expression : 3 4 5 * 6 / +
Example:-
A * (B + C * D) + E becomes A B C D * + * E +
current symbol operator stack postfix string

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+
A summary of the rules follows:
1. Print operands as they arrive.
2. If the stack is empty or contains a left parenthesis on top, push the incoming operator onto the
stack.
3. If the incoming symbol is a left parenthesis, push it on the stack.
4. If the incoming symbol is a right parenthesis, pop the stack and print the operators until you see
a left parenthesis. Discard the pair of parentheses.
5. If the incoming symbol has higher precedence than the top of the stack, push it on the stack.
6. If the incoming symbol has equal precedence with the top of the stack, use association. If the
association is left to right, pop and print the top of the stack and then push the incoming operator.
If the association is right to left, push the incoming operator.
7. If the incoming symbol has lower precedence than the symbol on the top of the stack, pop the
stack and print the top operator. Then test the incoming operator against the new top of stack.
8. At the end of the expression, pop and print all operators on the stack. (No parentheses should
remain.)

Complexity
The time and space complexity of Conversion of Infix expression to Postfix expression algorithm is :
 Worst case time complexity:O(n^2)
 Average case time complexity: O(n^2)
 Best case time complexity: O(n^2)
 Space complexity: Θ(n)
where N is the number of literals in Infix Expression
 Complexity of algorithm in both worst and best case is O(n^2), as expression is iterated two times
simultaneously, firstly for scanning the infix expression and secondly while poping out of stack.
Eg : a + b - d
* As in above Infix expression, O(n) will be the complexity for scanning each literal, while at the same time
we pop the literals from stack, hence the complexity of algorithm is O(n*n) i.e : O(n^2).
 For storing Infix expression of n literals the space complexity is O(n) and for stack to hold atmost n literals the
space complexity is O(n), hence
* Total space complexity is O(n+n) = O(2n) i.e : O(n)

You might also like