0% found this document useful (0 votes)
14 views18 pages

DS Unit-3 (R23)

Stacks are linear data structures that follow the Last-In-First-Out (LIFO) principle, allowing elements to be added and removed only from the top. Key operations include push (to add), pop (to remove), and peek (to view the top element), with overflow and underflow conditions indicating full and empty states, respectively. Stacks can be implemented using arrays or linked lists and have applications in reversing lists and evaluating expressions.

Uploaded by

rvsnr2505
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)
14 views18 pages

DS Unit-3 (R23)

Stacks are linear data structures that follow the Last-In-First-Out (LIFO) principle, allowing elements to be added and removed only from the top. Key operations include push (to add), pop (to remove), and peek (to view the top element), with overflow and underflow conditions indicating full and empty states, respectively. Stacks can be implemented using arrays or linked lists and have applications in reversing lists and evaluating expressions.

Uploaded by

rvsnr2505
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

UNIT-3

STACKS

Stack is an important data structure which stores its elements in an ordered manner. A stack is a
linear data structure and the elements in a stack are added and removed only from one end,
which is called the TOP. Hence, a stack is called a LIFO (Last-In-First-Out) data structure, as the
element that was inserted last is the first one to be taken out. Stacks can be implemented using
either arrays or linked lists.

Basic features of Stack

1. Stack is an ordered list of similar data type.


2. Stack is a LIFO (Last in First out) structure or we can say FILO (First in Last out).
3. Push () function is used to insert new elements into the Stack and pop () function is used
to remove an element from the stack. Both insertion and removal are allowed at only one
end of Stack called Top.
4. Stack is said to be in Overflow state when it is completely full and is said to be
in Underflow state if it is completely empty.

DATA STRUCTURES UNIT-3[R23] Page 1


A stack can be visualized as follows:

ARRAY REPRESENTATION OF STACKS

In the computer’s memory, stacks can be represented as a linear array. Every stack has a variable
called TOP associated with it, which is used to store the address of the topmost element of the
stack. It is this position where the element will be added to or deleted from. There is another
variable called MAX, which is used to store the maximum number of elements that the stack can
hold. If TOP = NULL, then it indicates that the stack is empty and if TOP = MAX–1, then the
stack is full. Look at Fig.

The stack in Fig. above shows that TOP = 4, so insertions and deletions will be done at this
position. In the above stack, five more elements can still be stored.

OPERATIONS ON A STACK

A stack supports three basic operations: push, pop, and peek. The push operation adds an
element to the top of the stack and the pop operation removes the element from the top of the
stack. The peek operation returns the value of the topmost element of the stack.

a. Push Operation

The push operation is used to insert an element into the stack. The new element is added at the
topmost position of the stack. However, before inserting the value, we must first check if
TOP=MAX–1, because if that is the case, then the stack is full and no more insertions can be
done. If an attempt is made to insert a value in a stack that is already full, an OVERFLOW
message is printed. Consider the stack given in Fig.

DATA STRUCTURES UNIT-3[R23] Page 2


To insert an element with value 6, we first check if TOP=MAX–1. If the condition is false, then
we increment the value of TOP and store the new element at the position given by stack[TOP].
Thus, the updated stack becomes as shown in Fig.

Algorithm to insert an element in a stack

b. Pop Operation

The pop operation is used to delete the topmost element from the stack. However, before
deleting the value, we must first check if TOP=NULL because if that is the case, then it means
the stack is empty and no more deletions can be done. If an attempt is made to delete a value
from a stack that is already empty, an UNDERFLOW message is printed. Consider the stack
given in Fig.

To delete the topmost element, we first check if TOP=NULL. If the condition is false, then we
decrement the value pointed by TOP. Thus, the updated stack becomes as shown in Fig.

DATA STRUCTURES UNIT-3[R23] Page 3


Algorithm to delete an element from a stack

c. Peek Operation

Peek is an operation that returns the value of the topmost element of the stack without deleting it
from the stack. The algorithm for Peek operation is given in Fig.

However, the Peek operation first checks if the stack is empty, i.e., if TOP = NULL, then an
appropriate message is printed, else the value is returned. Consider the stack given in Fig. Here,
the Peek operation will return 5, as it is the value of the topmost element of the stack.

Algorithm for Peek operation

d. Verifying whether the Stack is full: isFull()


The isFull() operation checks whether the stack is full. This operation is used to check the status
of the stack with the help of top pointer.

Step 1: if top = = MAXSIZE


Print ―STACK IS FULL – OVERFLOW‖
STEP 2: END

DATA STRUCTURES UNIT-3[R23] Page 4


e. Verifying whether the Stack is empty: isEmpty()
The isEmpty() operation verifies whether the stack is empty. This operation is used to check the
status of the stack with the help of top pointer.

Step 1: if top = = -1
Print ―STACK IS EMPTY – UNDER FLOW‖
STEP 2: END

LINKED REPRESENTATION OF STACKS

In a linked stack, every node has two parts—one that stores data and another that stores the
address of the next node. The START pointer of the linked list is used as TOP. All insertions and
deletions are done at the node pointed by TOP. If TOP = NULL, then it indicates that the stack is
empty. The linked representation of a stack is shown in Fig.

Operations on a Linked Stack

A linked stack supports all the three stack operations, that is, push, pop, and peek.

a. Push Operation

The push operation is used to insert an element into the stack. The new element is added at the
topmost position of the stack. Consider the linked stack shown in Fig.

To insert an element with value 9, we first check if TOP=NULL. If this is the case, then we
allocate memory for a new node, store the value in its DATA part and NULL in its NEXT part.
The new node will then be called TOP. However, if TOP!=NULL, then we insert the new node
at the beginning of the linked stack and name this new node as TOP. Thus, the updated stack
becomes as shown in Fig.

DATA STRUCTURES UNIT-3[R23] Page 5


Algorithm to insert an element in a linked stack

b. Pop Operation

The pop operation is used to delete the topmost element from a stack. However, before deleting
the value, we must first check if TOP=NULL, because if this is the case, then it means that the
stack is empty and no more deletions can be done. If an attempt is made to delete a value from a
stack that is already empty, an UNDERFLOW message is printed. Consider the stack shown in
Fig.

In case TOP! =NULL, then we will delete the node pointed by TOP, and make TOP point to the
second element of the linked stack. Thus, the updated stack becomes as shown in Fig.

DATA STRUCTURES UNIT-3[R23] Page 6


Algorithm to delete an element from a linked stack

APPLICATIONS OF STACKS

a. Reversing a List
The idea of this approach is simple: traverse all the nodes one by one from the starting node of
the given linked list and push all the values of the nodes into the auxiliary stack.
We know that the stack Data Structure follows the LIFO(last in first out) order. So, if we extract
the content of the stack, we get the last element first, then the second last element and so on, i.e.
we get the data in reverse order.
Finally, we change the linked list data from starting with the reversed data from the stack one by
one for all nodes.
Steps:
1. Declare a stack.
2. Push all the values of the nodes from starting into the stack.
3. Change the values of the nodes from the beginning of the linked list with the top element of
the stack.
4. Move to the next node and pop the top element from the stack, and
5. Repeat steps 3 and 4 while the stack is not empty.

Let’s understand the above approach with an example:


Initially, the curr pointer points to the head of the linked list, and all the nodes are pushed into
the stack data structure.

DATA STRUCTURES UNIT-3[R23] Page 7


Now we replace, curr->data with the stack.top() element and move the curr pointer to the next
node and pop the top element of the stack.

Again repeat the above process by replacing curr->data with the stack.top() element and moving
the curr pointer to the next node and popping the top element of the stack.

DATA STRUCTURES UNIT-3[R23] Page 8


We keep on repeating this step until we reach the end node of the linked list.

Now, the stack is empty, and we get the required reversed linked list.

DATA STRUCTURES UNIT-3[R23] Page 9


Write a program to reverse a list of given numbers.

#include <stdio.h>
#include <conio.h>
int stk[10];
int top= –1;
int pop();
void push(int);
int main()
{
int val, n, i,
arr[10];
clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
printf("\n Enter the elements of the array : ");
for(i=0;i<n;i++)
scanf("%d", &arr[i]);
for(i=0;i<n;i++)
push(arr[i]);
for(i=0;i<n;i++)
{
val = pop();
arr[i] = val;
}
printf("\n The reversed array is : ");
for(i=0;i<n;i++)
printf("\n %d", arr[i]);
getche"();
return 0;
}

void push(int val)


{
stk[++top] = val;
}
int pop()
{
return(stk[top––]);
}

DATA STRUCTURES UNIT-3[R23] Page 10


Output
Enter the number of elements in the array: 5
Enter the elements of the array: 1 2 3 4 5
The reversed array is: 5 4 3 2 1

b.)EXPRESSIONS
An expression is a mathematical statement that includes numbers, variables, and
operations. Expressions can include addition, subtraction, multiplication, division, exponents,
and roots. The way to write arithmetic expression is known as a notation. An arithmetic
expression can be written in three different but equivalent notations, i.e., without changing the
essence or output of an expression. These notations are −

 Infix Notation
 Prefix (Polish) Notation
 Postfix (Reverse-Polish) Notation
These notations are named as how they use operator in expression. We shall learn the same here
in this chapter.

Infix Notation
We write expression in infix notation, e.g. a - b + c, where operators are used in-between
operands. It is easy for us humans to read, write, and speak in infix notation but the same does
not go well with computing devices.

Prefix Notation
In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For
example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known
as Polish Notation.

Postfix Notation
This notation style is known as Reversed Polish Notation. In this notation style, the operator
is postfixed to the operands i.e., the operator is written after the operands. For example, ab+.
This is equivalent to its infix notation a + b.
Infix to Postfix Conversion

Let I be an algebraic expression written in infix notation. I may contain parentheses, operands,
and operators. For simplicity of the algorithm we will use only +, –, *, /, % operators. The
precedence of these operators can be given as follows:

Higher priority : *, /, % Lower priority : +, –

DATA STRUCTURES UNIT-3[R23] Page 11


No doubt, the order of evaluation of these operators can be changed by making use of
parentheses. For example, if we have an expression A + B * C, then first B * C will be done and
the result will be added to A. But the same expression if written as, (A + B) * C, will evaluate A
+ B first and then the result will be multiplied with C.

Algorithm to convert Infix to Postfix


STEP 1: Start
STEP 2: Read the infix expression from left to right.
STEP 3: If the input symbol is an operand, append it to the postfix expression.
STEP 4: If the input symbol is an operator, do the following:

(a) While the stack is not empty and the top of the stack is an operator, check precedence:

 If the precedence of the top operator is greater than or equal to the incoming
operator:
 For left-to-right associative operators (+, -, *, /) → pop and append to
postfix.
 For right-to-left associative operators (^) → do not pop, directly push the
incoming operator.

(b) Push the incoming operator onto the stack.


(c) If the input operator is '(', push it onto the stack.
(d) If the input operator is ')', pop from the stack and append to postfix until '(' is
encountered.
STEP 5: Repeat steps 2, 3, and 4 until the end of the expression.
STEP 6: Pop all remaining operators from the stack and append them to the postfix expression.
STEP 7: Print the postfix expression as a result.
STEP 8: Stop

Example:-

Convert the following infix expression into postfix expression using the algorithm given
A – (B / C + (D % E * F) / G)* H

Infix Character Stack (Operators) Postfix Expression (Operands & Operators)


(
A (- A
- (- A
( (-( A
B (-( AB
/ (-(/ AB

DATA STRUCTURES UNIT-3[R23] Page 12


Infix Character Stack (Operators) Postfix Expression (Operands & Operators)
C (-(/ ABC
+ (-(+ ABC/
( (-(+( ABC/
D (-(+( ABC/D
% (-(+(% ABC/D
E (-(+(% ABC/DE
* (-(+(* ABC/DE%
F (-(+(* ABC/DE%F
) (-(+ ABC/DE%F*
/ (-(+/ ABC/DE%F*
G (-(+/ ABC/DE%F*G
) (-( ABC/DE%F*G/+
* (-* ABC/DE%F*G/+
H (-* ABC/DE%F*G/+H
) (- ABC/DE%F*G/+H*
End of Expression - ABC/DE%F*G/+H*-

Example 2: A + B * C - D / E

Symbol Stack Postfix


A A
+ + A
B + AB
* +* AB
C +* ABC
- - ABC*+
D - ABC*+D
/ -/ ABC*+D
E -/ ABC*+DE
(End) ABC*+DE/-

DATA STRUCTURES UNIT-3[R23] Page 13


c.) Evaluation of a Postfix Expression

Converting the infix notation into postfix notation and evaluating the postfix expression—make
extensive use of stacks as the primary tool. Using stacks, any postfix expression can be evaluated
very easily. Every character of the postfix expression is scanned from left to right. If the
character encountered is an operand, it is pushed on to the stack. However, if an operator is
encountered, then the top two values are popped from the stack and the operator is applied on
these values. The result is then pushed on to the stack.

Algorithm to evaluate a postfix expression

STEP 1: Add a ")" at the end of the postfix expression.


STEP 2: Scan each character in the postfix expression and repeat Steps 3 and 4 until ")" is
encountered.
STEP 3: Processing characters:
a) If an operand is encountered, push it onto the stack.
b) If an operator op is encountered:
i. Pop the top two elements from the stack as A and B, where A is the topmost
element and B is the one below it.
ii. Evaluate B op A.
iii. Push the result of evaluation onto the stack.

STEP 4: Set RESULT equal to the topmost element of the stack.


STEP 5: Exit.

DATA STRUCTURES UNIT-3[R23] Page 14


Example :-

DATA STRUCTURES UNIT-3[R23] Page 15


d.) Backtracking

Backtracking is a general algorithmic technique that is often used in data structures to solve
problems recursively by trying out various possible solutions and then undoing them if they do
not lead to a solution.

Depth First Search (DFS) Algorithm

Depth First Search (DFS) algorithm is used for searching all the vertices of a graph or tree data
structure. This algorithm traverses a graph in a depth ward motion and uses a stack to remember
to get the next vertex to start a search, when a dead end occurs in any iteration.

Algorithm

 Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a
stack.
 Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all
the vertices from the stack, which do not have adjacent vertices.)
 Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.

Step Traversal Description

1 Initialize the stack.

Mark S as visited and put it


onto the stack. Explore any
unvisited adjacent node
from S. We have three nodes
2
and we can pick any of them.
For this example, we shall
take the node in an
alphabetical order.

DATA STRUCTURES UNIT-3[R23] Page 16


Mark A as visited and put it
onto the stack. Explore any
unvisited adjacent node from
3
A. Both S and D are adjacent
to A but we are concerned for
unvisited nodes only.

Visit D and mark it as visited


and put onto the stack. Here,
we have B and C nodes,
4 which are adjacent to D and
both are unvisited. However,
we shall again choose in an
alphabetical order.

We choose B, mark it as
visited and put onto the stack.
5 Here B does not have any
unvisited adjacent node. So,
we pop B from the stack.

We check the stack top for


return to the previous node
and check if it has any
6
unvisited nodes. Here, we
find D to be on the top of the
stack.

DATA STRUCTURES UNIT-3[R23] Page 17


Only unvisited adjacent node
is from D is C now. So we
7
visit C, mark it as visited and
put it onto the stack.

As C does not have any unvisited adjacent node so we keep popping the stack until we find a
node that has an unvisited adjacent node. In this case, there's none and we keep popping until the
stack is empty.

Algorithm:-

Step 1: Initialize an empty stack.


Step 2: Choose a starting vertex, mark it as visited, and push it onto the stack.
Step 3: While the stack is not empty:
i). Peek at the top vertex in the stack.
ii). If it has an unvisited adjacent vertex, mark that vertex as visited and push it onto
the stack.
iii). If there are no unvisited adjacent vertices, pop the top vertex from the stack
(backtracking).
Step 4: Repeat Step 3 until the stack is empty.

DATA STRUCTURES UNIT-3[R23] Page 18

You might also like