0% found this document useful (0 votes)
58 views37 pages

DSA Chapter 4

The document discusses stacks and their applications. It describes what a stack is, the common stack operations like push, pop, peek etc. It also covers stack implementations using arrays and linked lists. Finally, it provides examples of applications of stacks like reversing a string, undo-redo operations, expression conversion etc.

Uploaded by

F&B House
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views37 pages

DSA Chapter 4

The document discusses stacks and their applications. It describes what a stack is, the common stack operations like push, pop, peek etc. It also covers stack implementations using arrays and linked lists. Finally, it provides examples of applications of stacks like reversing a string, undo-redo operations, expression conversion etc.

Uploaded by

F&B House
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Chapter Four

Stacks & Its Applications

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.

• Stack is a more restricted List with the following


constraints:
– Elements are stored by order of insertion from "bottom" to
"top“.
– Items are added to the top.
– Only the last element added onto the stack (the top element)
can be accessed or removed.

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.

• In an array implementation of pop() operation, the


data element is not actually removed, instead top is
decremented to a lower position in the stack to point
to the next value.

• But in linked-list implementation, pop() actually


removes data element and deallocates memory space.

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.

• Top is pointing to index number 3, which means


stack has four items.
15
Stack implementation: Array
Push operation Pop operation
void push(int newdata) { int pop(int data) {
if(!isFull()) { if(!isempty()) {
top = top + 1; data = stack[top];
stack[top] = newdata; top = top - 1;
} return data;
else { }
cout<<"Stack is full.\n"); else {
} cout<<“\nStack is empty\n";
} }
}
16
Stack implementation: Linked list
• Instead of using array, we can also
use linked list to implement stack.
• Linked list allocates the memory
dynamically.
• In linked list implementation of
stack, the nodes are maintained non-
contiguously in the memory.
• Each node contains a pointer to its
immediate successor node in the
stack.
• Top is a reference to the head of a
linked list of items.
17
Stack implementation: Linked list
Push Operation
bool isEmpty(){
return (topPtr == NULL);
}
void push(dataType newItem)
{
// create a new node
StackNode *newPtr = new StackNode;
// set data portion of new node
newPtr->item = newItem;
// insert the new node
newPtr->next = topPtr;
topPtr = newPtr; 18
}
Stack implementation: Linked list
Pop Operation
dataType pop()
{
if (isEmpty())
cout<<“Stack is empty…!”;
// not empty; retrieve and delete top
else{
stackTOp = topPtr->item;
StackNode *temp = topPtr;
topPtr = topPtr->next;
// return deleted node to system
temp->next = NULL; // safeguard
delete temp;
return stackTOp;
}
} 19
Comparing Implementations
• An array-based implementation:
– Prevents the push operation from adding an item
to the stack if the stack’s size limit has been
reached.

• A pointer-based (Linked list) implementation.


– Does not put a limit on the size of the stack.

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

Mathematical Expression C++ Expression

• Naturally, we compute: parenthesis first, precedence.


• Develop an algorithm to do the same?
– Possible but complex!

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 + is read (binary operator), pop 3 & 2, push their


sum 5 onto the stack:

• Next 8 is pushed

30
• Next item is * : (8 & 5 popped, 40 pushed)
6523+8*+3+*
• Next the operator + followed by 3:

(40 & 5 popped, 45 pushed, 3 pushed)

• Next is + , pop 3 & 45 and push 45+3=48

• Next is *, pop 48 & 6 ,and push 6*48=288

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

Infix operator stack postfix


3+2*4 empty empty
+2*4 empty 3
2*4 + 3
*4 + 32
4 +* 32
+* 324
+ 324*
empty 324*+

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.

Precedence Priority of operators:


 Priority 4: ‘(‘ - only popped if a matching ‘)’ is found.
 Priority 3: All unary operators (-, sin, cosin,….)
 Priority 2: / *
 Priority 1: + - 35
Algorithm to Convert Infix to Postfix
Example 1: A + B * C - D / E

Infix Stack(bottom->top) Postfix


A+B* C -D /E empty empty
a) + B * C - D / E empty A
b) B*C-D/E + A
c) *C-D/E + AB
d) C-D/E +* AB
e) -D/E +* ABC
f) D/E +- ABC * +
g) /E - ABC * +D
h) E -/ ABC * +D
i) -/ ABC * +D E
j) empty ABC * +D E/-

36
Thank You

Question?

37

You might also like