0% found this document useful (0 votes)
1 views24 pages

Unit 3 Stack

This document provides an introduction to stacks, a linear data structure that follows the Last In First Out (LIFO) principle for insertion and deletion operations. It covers the basic operations of stacks, including push, pop, and peek, as well as their implementation using arrays and linked lists. Additionally, the document discusses applications of stacks in various scenarios such as expression evaluation, backtracking, and memory management.

Uploaded by

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

Unit 3 Stack

This document provides an introduction to stacks, a linear data structure that follows the Last In First Out (LIFO) principle for insertion and deletion operations. It covers the basic operations of stacks, including push, pop, and peek, as well as their implementation using arrays and linked lists. Additionally, the document discusses applications of stacks in various scenarios such as expression evaluation, backtracking, and memory management.

Uploaded by

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

Unit – III

Syllabus:

………………………………………………………………………………………………………………………………………….
INTRODUCTION TO STACK:

What is a Stack?
Stack is a linear data structure in which the insertion and deletion operations are performed at only one end.
In a stack, adding and removing of elements are performed at a single position which is known as "top". That
means, a new element is added at top of the stack and an element is removed from the top of the stack.

In stack, the insertion and deletion operations are performed based on LIFO (Last In First Out)
principle.
A stack data structure can be defined as follows...
Stack is a linear data structure in which the operations are performed based on LIFO principle.
Stack can also be defined as
"A Collection of similar data items in which both insertion and deletion operations are performed based
on LIFO principle".

In a stack, the insertion operation is performed using a function called "push" and deletion operation is
performed using a function called "pop".

In the figure, PUSH and POP operations are performed at a top position in the stack. That means, both the
insertion and deletion operations are performed at one end (i.e., at Top)

When a stack is completely full, it is said to be Stack is Overflow and if stack is completely empty, it is said to be
Stack is Underflow

1
PROPERTIES OF STACK:
There are following important properties of stack-

(i) All insertions and deletions can occur only at the top of stack.

(ii) The elements that are removed from stack in reverse order in which they were inserted.

(iii) Only one element can be pushed or popped from the stack at a time.

(iv) It works in last-in-first-out or LIFO manner.

2
OPERATIONS ON STACKS:

The basic operations performed in a Stack:


1. Push(x) - add element x at the top of the stack
2. Pop( ) - remove top element from the stack
3. peek() - get top element of the stack without removing it

Algorithm for PUSH operation:

1. Check if the stack is full or not.


2. If the stack is full, then print error of overflow and exit the program.
3. If the stack is not full, then increment the top and add the element at top location.

Algorithm for POP operation

1. Check if the stack is empty or not.


2. If the stack is empty, then print error of underflow and exit the program.
3. If the stack is not empty, then print the element at the top and decrement the top.

3
Algorithm for PEEK operation

1. Check if the stack is empty or not.


2. If the stack is empty, then print error of underflow and exit the program.
3. If the stack is not empty, then print the element at the top without removing it.

Implementing stack using arrays:

Here are the following operations of implement stack using array:

Push Operation in Stack:

Adds an item to the stack. If the stack is full, then it is said to be an Overflow condition.

 Before pushing the element to the stack, we check if the stack is full .

4
 If the stack is full (top == capacity-1) , then Stack Overflows and we cannot insert the element to the stack.

 Otherwise, we increment the value of top by 1 (top = top + 1) and the new value is inserted at top position .

 The elements can be pushed into the stack till we reach the capacity of the stack.

5
Pop Operation in Stack:
Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the
stack is empty, then it is said to be an Underflow condition.

 Before popping the element from the stack, we check if the stack is empty .

 If the stack is empty (top == -1), then Stack Underflows and we cannot remove any element from the stack.

 Otherwise, we store the value at top, decrement the value of top by 1 (top = top – 1) and return the stored top
value.

6
7
Top or Peek Operation in Stack:

Returns the top element of the stack.

 Before returning the top element from the stack, we check if the stack is empty.

 If the stack is empty (top == -1), we simply print “Stack is empty”.

 Otherwise, we return the element stored at index = top .

isEmpty Operation in Stack:

Returns true if the stack is empty, else false

 Check for the value of top in stack.

 If (top == -1) , then the stack is empty so return true .

 Otherwise, the stack is not empty so return false .

isFull Operation in Stack :

Returns true if the stack is full, else false.


8
 Check for the value of top in stack.

 If (top == size -1), then the stack is full so return true .

 Otherwise, the stack is not full so return false.

Implementation of stack using linked list:


Stack Using Linked List:
• The major problem with the stack implemented using an array is, it works
only for a fixed number of data values.
• A stack data structure can be implemented by using a linked list data
structure.
• it can work for an unlimited number of values. That means, stack
implemented using linked list works for the variable size of data. So, there is
no need to fix the size at the beginning of the implementation.
• The Stack implemented using linked list can organize as many data values as
we want.
The linked representation of a stack is

 In a linked stack, each node of the stack consists of two parts i.e. data part and the next part.
Each element of the stack points to its immediate next element in the memory.
 In the linked stack, there one pointer maintained in the
memory i.e. TOP pointer. The TOP pointer contains the
address of the starting element of the STACK.
 Both Insertion and deletions are performed at only one end
called TOP. If TOP is NULL, it indicates that the stack is empty. Initially

struct node *TOP = NULL ;


Operation on Linked STACK: There are two basic operations which can be implemented on the
linked queues. The operations are PUSH and POP.

PUSH function: PUSH function will add the element at the beginning of the linked list.
1. Declare a new node and allocate memory for it.
2. If TOP == NULL, make TOP points to the new node.
3. Otherwise, add the new node at TOP end and makes the next of new node is previous TOP.

9
POP function: POP function will remove the TOP element from the STACK.

We can use the following steps to delete a node from the stack...

Step 1 - Check whether stack is Empty (top == NULL).


Step 2 - If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and terminate the
function
Step 3 - If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
Step 4 - Then set 'top = top → next'.
Step 5 - Finally, delete 'temp'. (free(temp)).

Algorithms:

Or

void pop() {

if(top == NULL)

printf("\nStack is Empty!\n");

else {

struct Node *temp = top;

printf("\nDeleted element: %d", temp->data);

top = temp->next;

free(temp);

10
Logic :

void push(int value) { struct Node *newNode;

newNode = (struct Node*)malloc(sizeof(struct Node));

if (newNode == NULL) {

printf("Memory allocation failed!\n");

return;

newNode->data = value;

if(top == NULL)

newNode->next = NULL;

else

newNode->next = top;

top = newNode;

printf("\nInsertion successful!\n");

Applications of stack;
• Expression Evaluation and Conversion (Infix to Postfix/Prefix).
• Function Call Management (Call Stack for Recursion).
• Undo and Redo Operations in text editors and applications.
• Browser Navigation (Back and Forward Buttons).
• Parentheses Matching and Syntax Parsing in compilers.
• Memory Management (Runtime Stack in Memory Allocation).
• Depth-First Search (DFS) in graphs and trees.
• Tower of Hanoi Problem (Recursive Stack Simulation).
• Backtracking Problems (e.g., maze solving, Sudoku).
• Expression Tree Construction for arithmetic expressions.
• Virtual Machine and CPU Operations (Stack-Based Machines).
• Reversing a String using stack operations (push and pop).
• Factorial calculations

11
Applications of Stacks (other examples)
✔ Stack is used to reversing the given string.
✔ Stack is used to evaluate a postfix expression.

✔ Stack is used to convert an infix expression into postfix/prefix form.

✔ Stack is used to matching the parentheses in an expression.

Reversing list:
A list of numbers or string can be reversed by using the stack, perform the following steps
1. Reading the elements from the array and pushed into the stack.
2. Pop the elements and again stored into the array starting from first index
Algorithm: Example:

Stack in Backtracking
A stack can be used to implement the backtracking
mechanism efficiently. In this approach, every decision (state) is pushed onto the
stack. If the current path leads to a solution, we continue, but if it doesn't, we pop
from the stack to backtrack and try other options.
Steps in Backtracking with Stack:
1. Push the current state/decision onto the stack.
2. Check if the current state is valid.
1. If yes, explore the next step.
2. If no, pop the state and backtrack.
3.Repeat until a solution is found or all possibilities are exhausted
Real time example
1. Solving a Maze or Navigating a Map (GPS-based Pathfinding)
Scenario: Imagine you're navigating through a complex city using GPS, and you
encounter several dead-end streets. A GPS algorithm must backtrack when it

12
reaches a blocked road to explore alternate paths.
Backtracking with Stack:
• Each intersection (decision point) is pushed onto the stack.
• If a path leads to a dead end, it pops the last decision and tries other routes.
• Eventually, it finds the shortest path or exits when all possibilities are
explored.
Real-Time Backtracking with Stack Applications

1. Maze Navigation (Robots/Self-Driving Cars)


1. Push coordinates onto stack; backtrack on hitting dead ends.
2. Sudoku Solver
1. Push number placements; backtrack if constraints are violated.
3. Route Optimization (GPS)
1. Push potential routes; backtrack when encountering blocked paths.

4.Robot Vacuum Cleaner (Path Planning)


1.Push paths; backtrack if an obstacle is hit.

Evaluation of Expressions:-

What is an Expression?

In any programming language, if we want to perform any calculation or to frame a condition etc., we use a set of

symbols to perform the task. These set of symbols makes an expression.

An expression can be defined as follows...

An expression is a collection of operators and operands that represents a specific value.

In above definition, operator is a symbol which performs a particular task like arithmetic operation or logical operation

or conditional operation etc.,

Operands are the values on which the operators can perform the task. Here operand can be a direct value or variable

or address of memory location.

Expression Types

Based on the operator position, expressions are divided into THREE types. They are as follows...

1. Infix Expression

2. Postfix Expression

13
3. Prefix Expression

Infix Expression

In infix expression, operator is used in between the operands.

The general structure of an Infix expression is as follows...

Operand1 Operator Operand2

Example

Postfix Expression

In postfix expression, operator is used after operands. We can say that "Operator follows the Operands".

The general structure of Postfix expression is as follows...

Operand1 Operand2 Operator

Example

Prefix Expression

In prefix expression, operator is used before operands. We can say that "Operands follows the Operator".

The general structure of Prefix expression is as follows...

Operator Operand1 Operand2

Example

Every expression can be represented using all the above three different types of expressions. And we can convert an

expression from one form to another form like Infix to Postfix, Infix to Prefix, Prefix to Postfix and vice versa.

14
Operator Precedence: When an expression consist different level of operators we follow it. We
consider five binary operations: +, -, *, / and ^ (exponentiation). For these binary operations, the
following in the order of precedence (highest to lowest): ^ , * , /, +, -

Operator Associativity: When an expression consist more than one same level precedence operators
we follow it.
Basically we have Left to Right associativity and Right to Left Associativity. Most of the operators
are follows Left to Right but some of the operators are follow Right to left Associativity like Unary
(+/-), ++/-- , Logical negation (!), Pointer and address (*,&), Conditional Operators and Assignment
operators(=,+=,-=,*=,/=,%=).
Example: x=a/b–c+d*e–a*c

Let a = 4, b = c = 2, d = e = 3 then the value of x is found as

= ((4 / 2) – 2) + (3 * 3) – (4 * 2) =0+9–8 =1

Infix to Postfix Conversion


Any expression can be represented using three types of expressions (Infix, Postfix, and Prefix). We can also convert

one type of expression to another type of expression like Infix to Postfix, Infix to Prefix, Postfix to Prefix and vice

versa.

To convert any Infix expression into Postfix or Prefix expression we can use the following procedure...

1. Find all the operators in the given Infix Expression.

2. Find the order of operators evaluated according to their Operator precedence.

3. Convert each operator into required type of expression (Postfix or Prefix) in the same order.

Example

Consider the following Infix Expression to be converted into Postfix Expression...

D=A+B*C

 Step 1 - The Operators in the given Infix Expression : = , + , *

 Step 2 - The Order of Operators according to their preference : * , + , =

 Step 3 - Now, convert the first operator * ----- D = A + B C *

 Step 4 - Convert the next operator + ----- D = A BC* +

 Step 5 - Convert the next operator = ----- D ABC*+ =

Finally, given Infix Expression is converted into Postfix Expression as follows...

15
DABC*+=

Infix to Postfix Conversion using Stack Data Structure


To convert Infix Expression into Postfix Expression using a stack data
structure, We can use the following steps...
1. Read all the symbols one by one from left to right in the given Infix
Expression.
2. If the reading symbol is operand, then directly print it to the result
(Output).
3. If the reading symbol is left parenthesis '(', then Push it on to the
Stack.
4. If the reading symbol is right parenthesis ')', then Pop all the contents
of stack until respective left parenthesis is poped and print each
poped symbol to the result.
5. If the reading symbol is operator (+ , - , * , / etc.,), then Push it on to
the Stack. However, first pop the operators which are already on the
stack that have higher or equal precedence than current operator and
print them to the result.
Example
Consider the following Infix Expression...

(A+B)*(C-D)
The given infix expression can be converted into postfix expression using Stack data Structure

16
follows...
The final Postfix Expression is as follows...

17
AB+CD-*
EXAMPLE:2

18
Example:3

infix expression A*(B*C+D*E)+F to convert the post fix expression

19
EVALUATION OF POSTFIX EXPRESSION:

A postfix expression is a collection of operators and operands in which the operator is placed after the operands. That

means, in a postfix expression the operator follows the operands.

Postfix Expression has following general structure...

Operand1 Operand2 Operator

Example

Postfix Expression Evaluation using Stack Data Structure

A postfix expression can be evaluated using the Stack data structure. To evaluate a postfix expression using Stack

data structure we can use the following steps...

1. Read all the symbols one by one from left to right in the given Postfix Expression

2. If the reading symbol is operand, then push it on to the Stack.

3. If the reading symbol is operator (+ , - , * , / etc.,), then perform TWO pop operations and store the two

popped oparands in two different variables (operand1 and operand2). Then perform reading symbol

operation using operand1 and operand2 and push result back on to the Stack.

4. Finally! perform a pop operation and display the popped value as final result.

Example

Consider the following Expression...

20
21
Final Result is 48

Example:02

Example:03

22
Conversion of Infix to Prefix using Stack

Here’s a simplified algorithm to convert an infix expression to prefix expression:

Algorithm to Convert Infix to Prefix:


1. Reverse the Infix Expression:
o Reverse the given infix expression.
o Reverse the parentheses (change ( to ) and vice versa).
2. Convert the Reversed Infix to Postfix:
o Use the standard method of converting infix to postfix (using a stack for
operators).
o Apply operator precedence and associativity rules.
3. Reverse the Postfix Expression:
o After obtaining the postfix expression, reverse it to get the prefix
expression.

Simple Steps:
1. Reverse the given infix expression.
2. Swap the parentheses (i.e., replace ( with ) and ) with ().
3. Convert the modified reversed expression to postfix.
4. Reverse the postfix expression to get the final prefix expression.
Given Infix - ((a/b)+c)-(d+(e*f))

 Step 1: Reverse the infix string. Note that while reversing the string you must interchange left and right parentheses.
 Step 2: Obtain the postfix expression of the expression obtained from Step 1.
 Step 3: Reverse the postfix expression to get the prefix expression

1. String after reversal – ))f*e(+d(-)c+)b/a((


2. String after interchanging right and left parenthesis – ((f*e)+d)-(c+(b/a))
3. Apply postfix – Below is postfix (On this page you check infix to postfix conversion rule)
4. Reverse Postfix Expression (Given After the image below)

23
Sr. No. Expression Stack Prefix
0 ( (
1 ( ((
2 f (( f
3 * ((* f
4 e ((* fe
5 ) ( fe*
6 + (+ fe*
7 d (+ fe*d
8 ) fe*d+
9 – – fe*d+
10 ( -( fe*d+
11 c -( fe*d+c
12 + -(+ fe*d+c
13 ( -(+( fe*d+c
14 b -(+( fe*d+cb
15 / -(+(/ fe*d+cb
16 a -(+(/ fe*d+cba
17 ) -(+ fe*d+cba/
18 ) – fe*d+cba/+
19 fe*d+cba/+-
Final prefix: -+/abc+d*ef

24

You might also like