DSA Chapter 4
DSA Chapter 4
1
Introduction
• A stack is a linear data structure that follows the
principle of Last In First Out (LIFO).
– This means the last element inserted inside the stack is
removed first.
• All deletions and insertions occur at one end of the
stack known as the TOP.
2
Introduction
• A stack is an Abstract Data Type (ADT), commonly
used in most programming languages.
3
Stack Operations
• push(): adding or putting an element on top of the
stack.
– If the stack is full, then the overflow condition occurs.
• pop(): removing or deleting an element from the top of
the stack.
– If the stack is empty means that no element exists in the stack,
this state is known as an underflow state.
• isEmpty(): It determines whether the stack is empty or
not.
• isFull(): It determines whether the stack is full or not.
• peek(): It returns the top data element of the stack
without removing it. 4
Stack Operations
• The operations work as follows:
– A pointer called TOP is used to keep track of the top element
in the stack.
– When initializing the stack, we set its value to -1 so that we
can check if the stack is empty by comparing TOP == -1.
– On pushing an element, we increase the value of TOP and
place the new element in the position pointed to by TOP.
– On popping an element, we return the element pointed to by
TOP and reduce its value.
– Before pushing, we check if the stack is already full
– Before popping, we check if the stack is already empty
5
Stack Operations: push()
• The process of putting a new data element onto stack is
known as a Push Operation.
• Push operation involves the following steps:
1. Checks if the stack is full or not.
2. If the stack is full, produces an error and exit.
3. If the stack is not full, increments top to point next empty
space.
4. Add the new data element to the stack location, where top is
pointing.
5. Returns success.
NB: If the linked list is used to implement the stack, then
in step 3, we need to allocate space dynamically. 6
Stack Operations: push()
7
Stack Operations: push()
Algorithm: void push(int data) {
begin procedure push: stack, data if(!isFull())
if stack is full {
return null top = top + 1;
endif stack[top] = data;
}
top ← top + 1 else
stack[top] ← data {
end procedure cout<<“\nStack is full\n");
}
}
8
Stack Operations: pop()
• Accessing the content while removing it from the
stack, is known as a Pop Operation.
9
Stack Operations: pop()
• Push operation involves the following steps:
1. Checks if the stack is empty or not
2. If the stack is empty, produces an error and exit.
3. If the stack is not empty, accesses the data element at
which top is pointing.
4. Decreases the value of top by 1.
5. Returns success.
10
Stack Operations: pop()
11
Stack Operations: pop()
Algorithm: int pop(int data) {
begin procedure pop: stack if(!isempty())
{
if stack is empty
data = stack[top];
return null
top = top - 1;
endif
return data;
}
data ← stack[top]
else {
top ← top - 1
cout<<“\nStack is empty\n";
return data
}
}
end procedure 12
Stack Operations: isfull(), isempty() & peek()
bool isfull() { int peek()
if(top == MAX_SIZE-1) {
return true; if(!isempty())
else return stack[top];
return false; else
} cout<<“\nStack is empty\n";
bool isempty(){ }
if(top == -1)
return true;
else
return false;
13
}
Stack implementation
• A Stack usually implemented using array or linked list.
14
Stack implementation: Array
• Stacks can be represented in memory using arrays.
• In array implementation, the stack is formed by using
the array.
• All the operations regarding the stack are performed
using arrays.
20
Applications of Stack
• String reversal:
– Stack is used for reversing a string.
– Put all the letters in a stack and pop them out.
– Because of the LIFO order of stack, you will get the letters
in reverse order.
• In browsers :
– The back button in a browser saves all the URLs you have
visited previously in a stack.
– Each time you visit a new page, it is added on top of the
stack.
– When you press the back button, the current URL is
removed from the stack, and the previous URL is
accessed.
21
Applications of Stack
• Balancing of symbols:
– Stack is used for balancing a symbol.
• UNDO/REDO:
– Stack can also be used for performing UNDO/REDO
operations.
• Expression conversion:
– Stack can also be used for expression conversion.
– Compilers use the stack to calculate the value of expressions
like 2 + 4 / 5 * (7 - 9) by converting the expression to prefix
or postfix form.
• ……
22
Applications of Stack: Expression conversion
• 4+5*5
• Simple calculation 45
• Scientific calculation 29
23
Solution: Re-expressing the Expression
• Restructure arithmetic expressions so that the order of
each calculation is embedded in the expression itself.
• Types of Expressions:
– Infix notation (A + B)
Used in Mathematics, suitable for humans
Rules: BODMAS…
– Prefix (Polish)notation (+AB)
C++ function: add(A, B)
– Postfix (Reverse-Polish) notation (AB+)
suitable for computers
Arithmetic and Logical Unit (ALU) designed
using this notation.
24
• The following table briefly tries to show the
difference in all three notations .
25
Advantages of Using Postfix Notation
• No need to apply operator precedence and other
rules.
• Parentheses are unnecessary.
• Easy for the computer (compiler) to evaluate an
arithmetic expression.
• The idea is taken from post-order traversal of an
expression tree.
26
Postfix Expression Evaluating Algorithm
• An algorithm exists to evaluate postfix expressions
using a stack.
• The single value on the stack is the desired result.
• Binary operators: +, -, *, /, etc.,
• Unary operators: unary minus, square root, sin, cos,
exp, etc.,
27
Postfix Evaluation
Psuedocode:
Operand: push
Operator: pop 2 operands for binary operator and 1
operand for unary operator, do the
math, push result back onto stack
123+*
Postfix Stack( bot -> top )
a) 1 2 3 + *
b) 2 3 + * 1
c) 3+* 12
d) +* 123
e) * 1 5 // 5 from 2 + 3
f) 5 // 5 from 1 * 5 28
initialize stack to empty;
while (not end of postfix expression) {
Postfix Evaluation get next postfix item;
Algorithm if (item is value)
push it onto the stack;
else if (item is binary operator) {
pop the stack to x;
pop the stack to y;
perform y operator x;
push the results onto the stack;
}
else if (item is unary operator) {
pop the stack to x;
perform operator(x);
push the results onto the stack
}
29
}
Example: 6 5 2 3 + 8 * + 3 + *
• Push items 6 through 3 6523+8*+3+*
• Next 8 is pushed
30
• Next item is * : (8 & 5 popped, 40 pushed)
6523+8*+3+*
• Next the operator + followed by 3:
31
Converting Infix to Postfix
• An algorithm to process infix notation could be
difficult and costly in terms of time and space
consumption.
• In high level languages, infix notation cannot be used
to evaluate expressions.
• We must analyze the expression to determine the
order in which we evaluate it.
• A common technique is to convert an infix notation
into postfix notation, then evaluating it.
32
Converting Infix to Postfix
• Convert A + B * C to postfix form:
A+B* C Infix Form
A + (B * C) Parenthesized expression
A + (B C *) Convert the multiplication
A (B C *) + Convert the addition
ABC* + Postfix form
Rules:
1.Parenthesize from left to light, higher precedence
operators parenthesized first.
2.The sub-expression (part of expression), which has
been converted into postfix, is treated as single
operand.
3.Once the expression is converted to postfix form,
remove the parenthesis. 33
Converting Infix to Postfix
Example (infix Expression): 3 + 2 * 4
34
Algorithm to Convert Infix to Postfix
Steps
1. Operands immediately go directly to output
2. Operators are pushed into the stack (including parenthesis)
Check to see if stack top operator is less than current operator
If the top operator is less than, push the current operator
onto stack
If the top operator is greater than the current, pop top operator
and append on postfix notation, push current operator onto
stack.
If we encounter a right parenthesis, pop from stack until we get
matching left parenthesis. Do not output parenthesis.
36
Thank You
Question?
37