0% found this document useful (0 votes)
33 views224 pages

Ds ch-2

Uploaded by

Vansh khatri
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)
33 views224 pages

Ds ch-2

Uploaded by

Vansh khatri
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/ 224

UNIT:-2

Linear Data Structure


ARRAY
Outline
❖ Array:-

One – Dimensional Array

Two – Dimensional Array

❖ Application of Array:-

Symbol Manipulation ( Matrix Representation of Polynomial Equation)

Sparse Matrix

❖ Sparse Matrix and its Representation


What is an Array?
❖ Arrays are defined as the collection of similar types of data items stored at contiguous
memory locations.

❖ It is one of the simplest data structures where each data element can be randomly
accessed by using its index number.

❖ For example, if we want to store the marks of a student in 6 subjects, then we don't
need to define a different variable for the marks in different subjects. Instead, we can
define an array that can store the marks in each subject at the contiguous memory
locations.
Representation of an Array

❖ As per the above illustration, there are some of the following important points -
Index starts with 0.
The array's length is 10, which means we can store 10 elements.
Each element in the array can be accessed via its index.
One - Dimensional Array
❖ Simplest data structure that makes use of computed address to locate its elements is the
one-dimensional array or vector.
❖ Number of memory locations is sequentially allocated to the vector.
❖ A vector size is fixed and therefore requires a fixed number of memory locations.
❖ Vector A with subscript lower bound of “one” is represented as below….
L0 is the address of the first word allocated to the first element of vector A
C words is size of each element or node L
The address of element Ai is
0
Loc(Ai) = L0 + (C*(i-1))
Let’s consider the more general case of a vector A with
L0+(i-1)C
lower bound for it’s subscript is given by some variable b.
The address of element Ai is A[i]
Loc(Ai) = L0 + (C*(i-b))
Calculating the Length of an Array
❖ The length of an array is given by the number of elements stored in it. The general
formula to calculate the length of an array is
Length = upper_bound – lower_bound + 1
❖ where upper_bound is the index of the last element and lower_bound is the index of the
first element in the array.
Lower Bound And Upper Bound In One
Dimensional Array
❖ Let suppose we have 1 dimensional array:
int A[6]={15,7,11,44,93,20};
❖ B = Base Address
❖ W = Storage size of one
element stored in array (in byte)
❖ I = Subscript of element whose
address is to be found
❖ Lb = Lower limit / Lower bound
of subscript, if not specified
Assume 0 (zero).
So, address of A[i] = B + W * ( I – Lb)
Calculating the Address of 1D Array
Elements
❖ The formula to perform this calculation is,

Address of A[k] = Base_Address(A) + w(k – Lower_Bound)

❖ Here, A is the array, k is the index of the element of which we have to calculate the address,
Base_Address is the base address of the array A, and w is the size of one element in
memory, for example, size of int is 2 bytes.
Address calculation in 1d array :
Example
❖ Example 1 : Given an array int marks[] = {99,67,78,56,88,90,34,85}, calculate the
address of marks[4] if the base address = 1000.

We know that storing an integer value requires 2 bytes, therefore, its size is 2 bytes.
Address of A[k] = Base_Address (A) + w(k – Lower_Bound)
marks[4]=1000+2(4–0)
=1000+2(4)
=1008 [Ans]
Address calculation in 1d array :
Example
❖ Example 2 : Base address of an array B[1300 : 1900] as 1020 and size of each element
of array is 2 bytes in the memory. Find the address of B[1700].
The given values are: Base_Address = 1020
Lower_Bound = 1300
w=2
k = 1700
We know that storing an integer value requires 2 bytes, therefore, its size is 2 bytes.
Address of A[k] = Base_Address(A) + w(k – Lower_Bound)
B[1700]=1020+2*(1700–1300)
=1020+2*400
=1020+800
=1820 [Ans]
Two - Dimensional Array
❖ Two dimensional arrays are also called table or matrix.
❖ Two dimensional arrays have two subscripts:-
Column Major Order Matrix
Row Major Order Matrix
❖ Column Major Order Matrix: Two dimensional array in which elements are stored
column by column is called as column major matrix.
❖ Two dimensional array consisting of two rows and four columns is stored sequentially by
columns :
A[1,1],A[2,1], A[1,2],A[2,2], A[1,3],A[2,3], A[1,4],A[2,4]
Calculating the Address of 2D Array
Elements (Column Major Order Matrix)
❖ Formula:-
A[I][J] = B.A. + Size * [(I-Lr) + R* (J-Lc)]
R = Ur – Lr + 1
Here,
B.A. = Base Address
I = Row Index of Element whose address to be calculated
J = Column Index of Element whose address to be calculated
Lr = Lower Bound of Row Index , Lc = Lower Bound of Column Index
Ur = Upper Bound of Row Index , Uc = Upper Bound of Column Index
Size = size (one element in array)
R = Total No. of Rows
Address calculation in 2d array :
Example ( Columns Major Matrix)
❖ Example 1 :Calculate the address of A[6][3] if the given array as A[9] [10] Base
address is 102. The array is floating type array. Here Elements are stored in column
major order.
Solution:-
Base Address = 102, I = 6, J = 3, Given Array A[9] [10] So, R=[9], C=[10]
In Array, A[9] [10] means range B[0…8] [0…9], Size = 4
So, Lr=Lc=0 and Ur = 8, Uc = 9
R = Ur – Lr + 1 = 8-0+1 = 9 So, R = 9
Formula:- A[I] [J] = B.A. + size * [ (I-Lr) + R* (J-Lc) ]
A[6] [3] = 102 + 4 * [ (6-0) + 9 (3-0) ]
= 102 + 4 * (33)
= 234 Answer
Two - Dimensional Array
❖ Row Major Order Matrix: Two dimensional array in which elements are stored row by
row is called as row major matrix.

b2 u2 m = no of rows
n = no of columns
b1
b1 = lower bound subscript of row
u1 = upper bound subscript of row
m = u1 – b1 + 1
u1
mxn b2 = lower bound subscript of column
u2 = upper bound subscript of column
n = u2 – b2 + 1
❖ The address element A [ i , j ] is given by
Loc (A [ i , j ]) = L0 + (i-1)*m + (j – 1)
❖ The address element A [ i , j ] is given by
Loc (A [ i , j ]) = L0 + (i-b1)*(u2-b2+1) + (j – b2)
Calculating the Address of 2D Array
Elements (Row Major Order Matrix)
❖ Example:-
A[I][J] = B.A. + Size * [ C* (I-Lr) + (J-Lc)]
C = Uc – Lc + 1
Here,
B.A. = Base Address
I = Row Index of Element whose address to be calculated
J = Column Index of Element whose address to be calculated
Lr = Lower Bound of Row Index , Lc = Lower Bound of Column Index
Ur = Upper Bound of Row Index , Uc = Upper Bound of Column Index
Size = size (one element in array)
C= Total No. of Columns
Address calculation in 2d array :
Example ( Row Major Matrix)
❖ Example 1 :Calculate the address of B[6][8] if the given array as B[11] [13] Base
address is 1000. The array is floating type array. Here Elements are stored in row major
order.
Solution:-
Base Address = 1000, I = 6, J = 8, Given Array B[11] [13] So, R=[11], C=[13]
In Array, B[11] [13] means range B[0…10] [0…12], Size = 4
So, Lr=Lc=0 and Ur = 10, Uc = 12
C = Uc – Lc + 1 = 12-0+1 = 13 So, C = 13
Formula:- A[I] [J] = B.A. + size * [ C * (I-Lr) + (J-Lc) ]
B[6] [8] = 1000 + 4 * [ 13 (6-0) + (8-0) ]
= 1000 + 4 * (108+8)
= 1344 Answer
Application of an Array
1. Symbol Manipulation (matrix representation of polynomial equation)
2. The array are also used for representing some sequential data structures such as a stack
and queue.
3. Sparse Matrix

❖ Matrix representation of polynomial equation:-


We can use array for different kind of operations in polynomial equation such as
addition, subtraction, division, differentiation etc…
We are interested in finding suitable representation for polynomial so that different
operations like addition, subtraction etc… can be performed in efficient manner.
Array can be used to represent Polynomial equation.
Representation of Polynomial Equation

2
2X + 5XY + Y 2 X2 + 3XY + Y2+Y-X

1 1 1
5 -1 3
1
Sparse Matrix
❖ An m x n matrix is said to be sparse if “many” of its elements are zero.
❖ A matrix that is not sparse is called a dense matrix.
❖ We can device a simple representation scheme whose space requirement equals the
size of the non-zero elements.

0 1 2 3 4 5 6 7 8
1 1 2 2 2 3 3 4 4
4 7 2 5 8 4 6 2 3
2 1 6 7 3 9 8 4 5
Sparse Matrix
❖ Example:-
Consider a matrix of size 100 X 100 containing only 10 non-zero elements.
In this matrix, only 10 spaces are filled with non-zero values and remaining spaces
of the matrix are filled with zero.
Totally we allocate 100 X 100 X 2 = 20000 bytes of space to store this integer
matrix.
To access these 10 non-zero elements we have to make scanning for 10000 times.
Why to use Sparse Matrix instead of
simple matrix ?
❖ Storage: There are lesser non-zero elements than zeros and thus lesser memory can be
used to store only those elements.
❖ Computing time: Computing time can be saved by logically designing a data structure
traversing only non-zero elements.
❖ Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes
in the matrix are of no use in most of the cases. So, instead of storing zeroes with
non-zero elements, we only store non-zero elements. This means storing non-zero
elements with triples- (Row, Column, value).
❖ Sparse Matrix Representations can be done in many ways following are two common
representations:
Array representation
Linked list representation
Why Sparse Matrix a better option over
a simple matrix?
❖ Operations of Sparse Matrix
We can perform 3 operations on Sparse Matrix
✔ Add
✔ Multiply
✔ Transpose
❖ To construct matrix structure from liner representation we need to record.
❖ Original row and columns of each non zero entries.
❖ Number of rows and columns in the matrix.
❖ So each element of the array into which the sparse matrix is mapped need to have three
fields: row, column and value.
Sparse Matrix
Linear representation of Matrix

1 3 6
1 5 9
A=
2 1 2
2 4 7
2 5 8
2 7 4
3 1 10
4 3 12
6 4 3
6 7 5
Memory Space required to store
Linear Representation

30 x 2 = 60 bytes
STACK
Outline
❖ STACK

❖ Application of STACK
❖ Operation of STACK
❖ Conversion of Expression :-
Infix to Postfix
Infix to Prefix
❖ Evaluate Expression:-
Postfix Expression
Prefix Expression
Infix Expression
❖ Recursion:-
GCD
Tower of Hanoi
STACK
❖ A linear list which allows insertion and deletion of an element at one end only is called
stack.
❖ The insertion operation is called as PUSH and deletion operation as POP.
❖ The most accessible elements in stack is known as TOP.
❖ The elements can only be removed in the opposite orders from that in which they were
added to the stack.
❖ Such a linear list is referred to as a LIFO (Last In First Out) list or FILO (First In
Last Out).
❖ A pointer TOP keeps track of the top element in the stack.
❖ Initially, when the stack is empty, TOP has a value of “zero”.
❖ Each time a new element is inserted in the stack, the pointer is incremented by “one”
before, the element is placed on the stack.
❖ The pointer is decremented by “one” each time a deletion is made from the stack.
STACK

Fig: Stack example Fig: push & pop operations


STACK Examples
STACK PUSH, POP & PEEK Operation
Application of STACK
❖ Recursion
❖ Keeping track of function calls
❖ Evaluation of expressions
❖ Reversing characters
❖ Servicing hardware interrupts
❖ Solving combinatorial problems using backtracking
❖ Expression Conversion (Infix to Postfix, Infix to Prefix)
❖ Game Playing (Chess)
❖ Microsoft Word (Undo / Redo)
❖ Compiler – Parsing syntax & expression
❖ Finding paths
Operations of STACK
1. PUSH:- Insert an element on TOP of the STACK
2. POP :- Remove Element from TOP of the STACK
3. PEEP :- Fetch ith element from Top of the STACK
4. CHANGE :- Change ith element from TOP of the STACK
STACK : PUSH Operation
STACK : POP Operation
STACK : PEEP Operation
STACK : PEEP Operation
STACK : CHANGE Operation
Expressions :- Infix, Prefix, Postfix
❖ There are three notations to represent an arithmetic expression:
Infix Notation :- Operand, Operator, Operand
Prefix Notation:- Operator, Operand, Operand
Postfix Notation :- Operand, Operand, Operator

❖ Infix Notation or Expression:-


❖ The infix notation is a convenient way of writing an expression in which each operator
is placed between the operands. Infix expressions can be parenthesized or
un-parenthesized depending upon the problem requirement.
❖ Example: A + B, (C - D) etc.
❖ All these expressions are in infix notation because the operator comes between the
operands.
Expressions :- Infix, Prefix, Postfix
❖ Prefix Notation or Expression (Polish Notation):-
❖ The prefix notation places the operator before the operands. This notation was
introduced by the Polish mathematician and hence often referred to as Polish
Notation.
❖ Example: + A B, -CD etc.
❖ All these expressions are in prefix notation because the operator comes before
the operands.
Expressions :- Infix, Prefix, Postfix
❖ Postfix Notation or Expression (Reverse Polish Notation):-
❖ The postfix notation places the operator after the operands. This notation is just
the reverse of Polish notation and also known as Reverse Polish notation.
❖ Example: AB +, CD+, etc.
❖ All these expressions are in prefix notation because the operator comes before
the operands.
Infix to Postfix Examples:-
Find the Rank of Expression:-
Convert Infix to Postfix Expression:-
Infix to postfix conversion
❖ Use a stack for processing operators (push and pop operations).
❖ Scan the sequence of operators and operands from left to right and perform one of the
following:
output the operand,
push an operator of higher precedence,
pop an operator and output, till the stack top contains operator of a lower
precedence and push the present operator.
Infix to postfix conversion
The algorithm steps
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.)
Infix to Postfix Conversion
❖ Requires operator precedence information:-
❖ Operands:
Add to postfix expression.
❖ Close parenthesis:
pop stack symbols until an open parenthesis appears.
❖ Operators:
Pop all stack symbols until a symbol of lower precedence appears. Then push
the operator.
❖ End of input:
Pop all remaining stack symbols and add to the expression.
Infix to Postfix Conversion
❖ A *(B*C+D*E)+F
Sr. no. Expression Stack Postfix
0 (
1 A ( A
2 ( A
3 * (* A
4 ( (*( A
5 B (*( AB
6 * (*(* AB
7 C (*(* A BC
8 + (*(+ A BC*
9 D (*(+ A BC*D
10 * (*(+* A BC*D
11 E (*(+* A BC*DE
12 ) (* A BC*DE*+
13 + (+ A BC*DE*+*
14 F (+ A BC*DE*+*F
15 ) A BC*DE*+*F+
Evaluate Postfix Expression
Evaluate Postfix Expression
Evaluate Postfix Expression
Evaluate Postfix Algorithm:-
Evaluate Postfix Expression
Task Examples:-
❖ Infix to Postfix Expression Conversion:-
1. (a+b^c^d)*(e+f/d)
2. (A + B * C / D - E + F / G / ( H + I ))

❖ Evaluate Postfix Expression:-


1. 6 5 3 + 9 * +
2. A B C + * D E / - ( A=5, B=6, C=2, D=12, E=4)
3. 5 4 6 + * 4 9 3 / + *
4. 7 5 2 + * 4 1 1 + / -
Task Examples Solutions:-
❖ (a+b^c^d)*(e+f/d)
Sr. no. Expression Stack Postfix
0 (
1 ( ((
2 a (( a
3 + ((+ a
4 b ((+ ab
5 ^ ((+^ ab
6 c ((+^ abc
7 ^ ((+^ abc^
8 d ((+^ abc^d
9 ) ( abc^d^+
10 * (* abc^d^+
11 ( (*( abc^d^+
12 e (*( abc^d^+e
13 + (*(+ abc^d^+e
14 f (*(+ abc^d^+ef
15 / (*(+/ abc^d^+ef
16 d (*(+/ abc^d^+efd
17 ) (* abc^d^+efd/+
18 ) abc^d^+efd/+*
Task Examples Solutions:-
❖ (A + B * C / D - E + F / G / ( H + I ))
Sr. no. Expression Stack Postfix
0 (
1 ( ((
2 A (( A
3 + ( (+ A
4 B ((+ AB
5 * ( ( +* AB
6 C ( ( +* ABC
7 / ( ( +/ ABC*
8 D ((+/ ABC*D
9 - ((- ABC*D/+
10 E ((- ABC*D/+E
11 + ((+ ABC*D/+E-
12 F ((+ ABC*D/+E-F
13 / ((+/ ABC*D/+E-F
14 G ((+/ ABC*D/+E-FG
15 / ((+/ ABC*D/+E-FG/
16 ( ( ( +/( ABC*D/+E-FG/
17 H ( ( +/( ABC*D/+E-FG/H
18 + ( ( +/(+ ABC*D/+E-FG/H
19 I ((+/(+ ABC*D/+E-FG/HI
20 ) ((+/ ABC*D/+E-FG/HI+

21 ) ( ABC*D/+E-FG/HI+/+

22 ) ABC*D/+E-FG/HI+/+
Task Examples Solution:-
Task Examples Solution:-
Task Examples Solution:-
Task Examples Solution:-
Task Examples Solution:-
Infix to Prefix Conversion
Infix to Prefix Conversion
Infix to Prefix Conversion:-
❖ Algorithm Approach:-
1. Reverse the infix expression
2. Make every ‘(‘ (Opening bracket) as ‘)’ (closing bracket) and ‘)’ as ‘(‘.
3. Convert the modified expression to postfix.
4. Reverse the postfix expression.

Infix Expression:- (a+b^c^d)*(e+f/d)


Reverse Expression:- (d/f+e)*(d^c^b+a)
Infix to Prefix Conversion:-
Sr. no. Expression Stack Postfix
0 (
1 ( ((
2 d (( d
3 / ((/ d
4 f ((/ df
5 + ((+ df/
6 e ((+ df/e
7 ) ( df/e+
8 * (* df/e+
9 ( (*( df/e+
10 d (*( df/e+d
11 ^ (*(^ df/e+d
12 c (*(^ df/e+dc
13 ^ (*(^ df/e+dc^
14 b (*(^ df/e+dc^b
15 + (*(+ df/e+dc^b^
16 a (*(+ df/e+dc^b^a
17 ) (* df/e+dc^b^a+
18 ) df/e+dc^b^a+*
Evaluate Prefix Algorithm:-
Evaluate Prefix Algorithm:-
Task Examples:-
❖ Evaluate Prefix Expression:-
1. - + / A ^ B C * D E * A C ( A=16, B=2, C=3, D=10, E=4)
2. + * A B – C + C * B A ( A=4, B = 8, C=12)
Task Examples Solutions:-
Task Examples Solutions:-
Task Examples Solutions:-
Stack Program Implementation:-
#include<stdio.h>
#include<conio.h>
#define MAX 3
int a[MAX], top = -1;
void push();
void pop();
void peep();
void change();
void display();
void main()
{
int ch;
clrscr();
while(1) {
Stack Program Implementation:-
printf("\n1. PUSH or INSERT");
printf("\n2. POP or DELETE");
printf("\n3. PEEP or SEARCH");
printf("\n4. CHANGE or UPDATE");
printf("\n5. Display");
printf("\n6. End program");
printf("\nEnter Choice : ");
scanf("%d",&ch);
clrscr();
switch(ch)
{
case 1:
{
push();
break;
}
Stack Program Implementation:-
case 2:
{
pop();
break;
}
case 3:
{
peep();
break;
}
case 4:
{
change();
break;
}
Stack Program Implementation:-
case 5:
{
display();
break;
}
case 6:
{
exit(0);
}
default:
printf("\ninvalid choice !!!");
} // switch close
getch();
}
//getch();
}
Stack Program Implementation:-
void push(){
int data;
if(top==MAX-1)
{
printf("\noverflow or stack is full !!!");
}
else
{
printf("\nEnter the element : ");
scanf("%d",&data);
top++;
a[top]=data;
}
}
Stack Program Implementation:-
void pop()
{
if(top==-1)
{
printf("\nunder flow STACK or STACK is empty");
}
else
{
printf("\nPOP or DELETE element : %d",a[top]);
top--;
}
}
Stack Program Implementation:-
void display()
{
int i;
if(top>=0)
{
printf("\nElemets : ");
for(i=top; i>=0; i--)
{
printf("\n%d",a[i]);
}
}
else
{
printf("\nThe STACK is Empty");
}
}
Stack Program Implementation:-
void peep()
{
int p;
printf("\nEnter the position : ");
scanf("%d",&p);
if(top-p<=-1)
{
printf("\nSTACK is overflow !!!");
}
else
{
printf("\nThe Elements is : %d",a[top-p]);
}
}
Stack Program Implementation:-
void change()
{
int v1,v2;
printf("\nEnter Position for change : ");
scanf("%d",&v1);
printf("\nEneter the Number for change : ");
scanf("%d",&v2);
if(top-v1<=-1)
{
printf("\nSTACK is overflow !!!");
}
else
{
a[top-v1]=v2;
printf("\nCHANGE successfull !!!");
}
}
Infix to Postfix Program Implementation:-
#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
Infix to Postfix Program Implementation:-
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
Infix to Postfix Program Implementation:-
printf("\n");
e = exp;
printf("Postfix expression : ");
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
Infix to Postfix Program Implementation:-
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}
return 0;
}
Recursion:-
Algorithm Factorial Number:-
Algorithm Factorial Number:-
Using Recursion Factorial Number:-
Using Recursion Factorial Number:-
GCD :- Greatest Common Divisior
❖ GCD or Greatest Common Divisor of two or more integers is the largest positive
integer that divides both the number without leaving any remainder.
❖ Example:-
❖ GCD of 20, 30 = 10 (10 is the largest number which divides 20 and 30 with remainder
as 0)
❖ GCD of 42, 120, 285 = 3 (3 is the largest number which divides 42, 120 and 285 with
remainder as 0)
❖ GCD (a , b) = b a%b=0
otherwise
❖ GCD (b, a % b)
GCD :- Greatest Common Divisior
int GCD( int a, int b)
{
int rem;
rem = a % b;
if ( rem == 0 )
{
return b;
}
else
{
GCD (b, rem);
}
}
GCD :- Greatest Common Divisior
❖ Example:-

1) GCD ( 64 , 8 ) = 64 % 8 => 0
Ans:- 8

2) GCD ( 64 , 6 ) = 64 % 6 => 4
GCD ( 6 , 4 ) = 6 % 4 => 2
GCD ( 4 , 2 ) = 4 % 2 => 0
Ans:- 2
GCD :- Greatest Common Divisior
Tower of Hanoi
❖ It is a classic problem where you try to move all the disks from one peg to another peg
using only three pegs.
❖ Initially, all of the disks are stacked on top of each other with larger disks under the
smaller disks.
❖ You may move the disks to any of three pegs as you attempt to relocate all of the disks,
but you cannot place the larger disks over smaller disks and only one disk can be
transferred at a time.
Tower of Hanoi

Example:- N=3 Move peg A to peg C

Move peg A to peg B Move peg C to peg B

Move peg A to peg C Move peg B to peg A

Move peg B to peg C


Tower of Hanoi
❖ In the above 7 step all the disks from peg A will be transferred to C given Condition:
❖ Only one disk will be shifted at a time.
❖ Smaller disk can be placed on larger disk.
❖ Let T (n) be the total time taken to move n disks from peg A to peg C
❖ Moving n-1 disks from the first peg to the second peg. This can be done in T (n-1) steps.
❖ Moving larger disks from the first peg to the third peg will require first one step.
❖ Recursively moving n-1 disks from the second peg to the third peg will require again T (n-1) step.
❖ In General if n-Disks are there than 2^n-1 steps count.

Disk Steps
1 1
2 3
3 7
n 2^n-1
Queue
Outline
❖ Queue

❖ Uses of Queue

❖ Operations of Queue

❖ Circular Queue

❖ Dequeue

❖ Priority Queue

❖ Application of Queue
Queue
❖ Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue
is open at both its ends. One end is always used to insert data (enqueue) and the other is
used to remove data (dequeue).
Queue
❖ Queue: a collection whose elements are added at one end (the rear or tail of the queue)
and removed from the other end (the front or head of the queue)
❖ A queue is a FIFO (first in, first out) data structure
❖ Any waiting line is a queue:
The check-out line at a grocery store
The cars at a stop light
An assembly line
Queue
Queue
Uses of Queues in Computing
❖ For any kind of problem involving FIFO data
❖ Printer queue (e.g. printer in MC 235)
❖ Keyboard input buffer
❖ GUI event queue (click on buttons, menu items)
❖ To encode messages (more on this later)

❖ In simulation studies, where the goal is to reduce waiting times:-


❖ Optimize the flow of traffic at a traffic light
❖ Determine number of cashiers to have on duty at a grocery store at different times of
day
Operations of Queues:-
Operations of Queues:-
Operations of Queues:-
Circular Queue:-
Circular Queue:-
Circular Queue:-
Dequeue:-
Dequeue:-
Dequeue:-
Dequeue:-
Priority Queue:-
❖ A priority queue is an abstract data type that behaves similarly to the normal queue
except that each element has some priority, i.e., the element with the highest priority
would come first in a priority queue.
❖ The priority of the elements in a priority queue will determine the order in which
elements are removed from the priority queue.
❖ The priority queue supports only comparable elements, which means that the
elements are either arranged in an ascending or descending order.
❖ For example, suppose we have some values like 1, 3, 4, 8, 14, 22 inserted in a
priority queue with an ordering imposed on the values is from least to the greatest.
Therefore, the 1 number would be having the highest priority while 22 will be
having the lowest priority.
Priority Queue:-
❖ Priorities of 1, 2, 3 have been attached with jobs of real time, online and batch
respectively. Therefore if a job is initiated with priority i,it is inserted immediately
at the end of list of other jobs with priorities i. Here jobs are always removed from
the front of queue
Priority Queue:-
Priority Queue:-
❖ Consider the following queue, where queue is a circular queue having 6 memory
cells. Front=2, Rear=4
❖ Queue: _, A, C, D, _, _

❖ Describe queue as following operation take place:


F is added to the queue
Two letters are deleted
R is added to the queue
S is added to the queue
One letter is deleted
Priority Queue:-
Recursion & Iteration:-
STACK & Queue
Queue Program:-
#include<stdio.h>
#include<conio.h>
#define n 5
void main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
//clrscr();
printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion
while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch);
Queue Program:-
switch(ch)
{
case 1:
if(rear==x)
printf("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==rear)
{
printf("\n Queue is empty");
}
Queue Program:-
else
{
printf("\n Deleted Element is %d",queue[front++]);
x++;
}
break;
case 3:
printf("\n Queue Elements are:
if(front==rear)
printf("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
Queue Program:-
}
break;
case 4:
exit(0);
default:
printf("Wrong Choice: please see the options");
}
}
}
}
Application of Queue:-
❖ CPU scheduling in operating systems
❖ Network packet scheduling
❖ Printer job scheduling
❖ Breadth-First Search (BFS) algorithm
❖ Simulation modelling
❖ Traffic management in communication networks
❖ Call center management
❖ Web server request handling
❖ Bank teller management
❖ Producer-consumer problem
LINK
LIST
Outline
❖ Link List

❖ Representation in Memory Link List

❖ Singly Link List

❖ Doubly Link List

❖ Circular Link List

❖ Operation of Link List

❖ Using Stack Link List

❖ Using Queue Link List

❖ Application of Link List


Link List
❖ There are many applications where sequential allocation method is unacceptable
because of following characteristics
Unpredictable storage requirement
Extensive manipulation of stored data
❖ One method of obtaining the address of node is to store address in computer’s main
memory, we refer this addressing mode as pointer of link addressing.
❖ A simple way to represent a linear list is to expand each node to contain a link or
pointer to the next node. This representation is called one-way chain or Singly
Linked Linear List.
Link List
❖ A linked list is a sequence of data structures, which are connected together via links.
❖ Linked List is a sequence of links which contains items. Each link contains a
connection to another link. Linked list is the second most-used data structure after
array. Following are the important terms to understand the concept of Linked List.
❖ Link − Each link of a linked list can store a data called an element.
❖ Next − Each link of a linked list contains a link to the next link called Next.
❖ LinkedList − A Linked List contains the connection link to the first link called First.
Node Structure
Singly Linked List
Link List

❖ The linked allocation method of storage can result in both efficient use of computer
storage and computer time.
A linked list is a non-sequential collection of data items.
Each node is divided into two parts, the first part represents the information of
the element and the second part contains the address of the next mode.
The last node of the list does not have successor node, so null value is stored as
the address.
It is possible for a list to have no nodes at all, such a list is called empty list.
Link List
❖ In a single linked list, the address of the first node is always stored in a reference
node known as "front" (Some times it is also known as "head").
❖ Always next part (reference part) of the last node must be NULL.
Operations Link List
❖ In a single linked list we perform the following operations...

Insertion

Deletion

Display
Insertion
❖ In a single linked list, the insertion operation can be performed in three
ways. They are as follows...

Inserting At Beginning of the list

Inserting At End of the list

Inserting At Specific location in the list


Inserting At Beginning of the list

❖ Step 1: Create a new Node with given value.


❖ Step 2: Check whether list is Empty (head == NULL)
❖ Step 3: If it is Empty then, set newNode→next = NULL and head = newNode.
❖ Step 4: If it is Not Empty then, set newNode→next = head and head = newNode.
Inserting At End of the list

❖ Step 1: Create a newNode with given value and newNode → next as NULL.
❖ Step 2: Check whether list is Empty (head == NULL).
❖ Step 3: If it is Empty then, set head = newNode.
❖ Step 4: If it is Not Empty then, define a node pointer temp and initialize with head.
❖ Step 5: Keep moving the temp to its next node until it reaches to the last node in the
list (until temp → next is equal to NULL).
❖ Step 6: Set temp → next = newNode.
Inserting At Specific location in the list
(After a Node)

❖ Step 1: Create a newNode with given value.


❖ Step 2: Check whether list is Empty (head == NULL)
❖ Step 3: If it is Empty then, set newNode → next = NULL and head = newNode.
❖ Step 4: If it is Not Empty then, define a node pointer temp and initialize with head.
Inserting At Specific location in the list
(After a Node)

❖Step 5: Keep moving the temp to its next node until it reaches to the node after which
we want to insert the newNode (until temp1 → data is equal to location, here location is
the node value after which we want to insert the newNode).
❖Step 6: Every time check whether temp is reached to last node or not. If it is reached
to last node then display 'Given node is not found in the list!!! Insertion not
possible!!!' and terminate the function. Otherwise move the temp to next node.
❖Step 7: Finally, Set 'newNode → next = temp → next' and 'temp → next =
newNode'
Deletion
❖ In a single linked list, the deletion operation can be performed in three ways.
They are as follows...

Deleting from Beginning of the list

Deleting from End of the list

Deleting a Specific Node


Deleting from Beginning of the list
Deleting from Beginning of the list
❖ Step 1: Check whether list is Empty (head == NULL)
❖ Step 2: If it is Empty then, display 'List is Empty!!! Deletion is
❖ not possible' and terminate the function.
❖ Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize with
head.
❖ Step 4: Check whether list is having only one node (temp → next == NULL)
❖ Step 5: If it is TRUE then set head = NULL and delete temp (Setting Empty
list conditions)
❖ Step 6: If it is FALSE then set head = temp → next, and delete temp.
Deleting from End of the list
Deleting from End of the list
❖ Step 1: Check whether list is Empty (head == NULL)
❖ Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
❖ Step 3: If it is Not Empty then, define two Node pointers 'temp1' and
'temp2' and initialize 'temp1' with head.
❖ Step 4: Check whetherlist has only one Node (temp1 →next == NULL)
❖ Step 5: If it is TRUE. Then, set head = NULL and delete temp1. And terminate the
function. (Setting Empty list condition)
❖ Step 6: If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next node.
Repeat the same until it reaches to the last node in the list. (until temp1 → next ==
NULL)
❖ Step 7: Finally, Set temp2 → next = NULL and delete temp1.
Deleting a Specific Node from the list
Deleting a Specific Node from the list
❖Step 1: Check whether list is Empty (head == NULL)
❖Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
❖Step 3: If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and
initialize 'temp1' with head.
❖Step 4: Keep moving the temp1 until it reaches to the exact node to be deleted or to
the last node. And every time set 'temp2 = temp1' before moving the 'temp1' to its next
node.
❖Step 5: If it is reached to the last node then display 'Given node not found in the list!
Deletion not possible!!!'. And terminate the function.
❖Step 6: If it is reached to the exact node which we want to delete, then check whether
list is having only one node or not
Deleting a Specific Node from the list
❖Step 7: If list has only one node and that is the node to be deleted, then set head =
NULL and delete temp1 (free(temp1)).
❖Step 8: If list contains multiple nodes, then check whether temp1 is the first node
in the list (temp1 == head).
❖Step 9: If temp1 is the first node then move the head to the next node (head = head
→ next) and delete temp1.
❖Step 10: If temp1 is not first node then check whether it is last node in the list (temp1
→ next == NULL).
❖Step 11: If temp1 is last node then set temp2 → next = NULL and delete temp1
(free(temp1)).
❖Step 12: If temp1 is not first node and not last node then set temp2 → next = temp1
→ next and delete temp1 (free(temp1)).
Displaying a Single Linked List
❖Step 1: Check whether list is Empty (head == NULL)
❖Step 2: If it is Empty then, display 'List is Empty!!!' and terminate the function.
❖Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize with head.
❖Step 4: Keep displaying temp → data with an arrow (--->) until temp
reaches to the last node
❖Step 5: Finally display temp → data with arrow pointing to NULL (temp
→ data ---> NULL).
Double or Doubly Linked List
❖ Double linked list is a sequence of elements in which every element has links to its
previous element and next element in the sequence.
❖ In double linked list, the first node must be always pointed by head.
❖ Always the previous field of the first node must be NULL.
❖ Always the next field of the last node must be NULL.
Double or Doubly Linked List Operations
❖ In a double linked list, we perform the following operations...

Insertion

Deletion

Display
Insertion
❖ In a double linked list, the insertion operation can be performed in three ways as
follows...

Inserting At Beginning of the list

Inserting At End of the list

Inserting At Specific location in the list


Inserting At Beginning of the list
Inserting At Beginning of the list
❖ Step 1: Create a newNode with given value and newNode → previous as NULL.

❖ Step 2: Check whether list is Empty (head == NULL)

❖ Step 3: If it is Empty then, assign NULL to newNode → next and newNode to head.

❖ Step 4: If it is not Empty then, assign head to newNode → next and newNode to head.
Inserting At End of the list
Inserting At End of the list
❖ Step 1: Create a newNode with given value and newNode → next as NULL.
❖ Step 2: Check whether list is Empty (head == NULL)
❖ Step 3: If it is Empty, then assign NULL to newNode → previous and newNode to
head.
❖ Step 4: If it is not Empty, then, define a node pointer temp and initialize with head.
❖ Step 5: Keep moving the temp to its next node until it reaches to the
❖ last node in the list (until temp → next is equal to NULL).
❖ Step 6: Assign newNode to temp → next and temp to newNode → previous.
Inserting At Specific location in the list
(After a Node)
Inserting At Specific location in the list
(After a Node)
❖ Step 1: Create a newNode with given value.
❖ Step 2: Check whether list is Empty (head == NULL)
❖ Step 3: If it is Empty then, assign NULL to newNode → previous & newNode →
next and newNode to head.
❖ Step 4: If it is not Empty then, define two node pointers temp1 & temp2 and
initialize temp1 with head.
❖ Step 5: Keep moving the temp1 to its next node until it reaches to the node after
which we want to insert the newNode (until temp1 → data is equal to location, here
location is the node value after which we want to insert the newNode).
Inserting At Specific location in the list
(After a Node)
❖ Step 6: Every time check whether temp1 is reached to the last node. If it is reached to
the last node then display 'Given node is not found in the list!!! Insertion not
possible!!!' and terminate the function. Otherwise move the temp1 to next node.
❖ Step 7: Assign temp1 → next to temp2, newNode to temp1→ next, temp1 to
newNode → previous, temp2 to newNode → next and newNode to temp2 →
previous.
Deletion
❖ In a double linked list, the deletion operation can be performed in three ways as
follows...

Deleting from Beginning of the list

Deleting from End of the list

Deleting from Specific location in the list


Deleting from Beginning of the list
Deleting from Beginning of the list
❖ Step 1: Check whether list is Empty (head == NULL)

❖ Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate
the function.

❖ Step 3: If it is not Empty then, define a Node pointer 'temp' and initialize with head.

❖ Step 4: Check whether list is having only one node (temp → previous is equal to temp →
next)

❖ Step 5: If it is TRUE, then set head to NULL and delete temp (Setting Empty list
conditions)
❖ Step 6: If it is FALSE, then assign temp →next to head, NULL to head → previous and
delete temp.
Deleting from End of the list
Deleting from End of the list
❖ Step 1: Check whether list is Empty (head == NULL)
❖ Step 2: If it is Empty, then display 'List is Empty!!! Deletion is not possible' and
terminate the function.
❖ Step 3: If it is not Empty then, define a Node pointer 'temp' and initialize with head.
❖ Step 4: Check whether list has only one Node (temp →previous and temp → next
both are NULL)
❖ Step 5: If it is TRUE, then assign NULL to head and delete temp. And terminate from
the function. (Setting Empty list condition)
❖ Step 6: If it is FALSE, then keep moving temp until it reaches to the last node in the
list. (until temp → next is equal to NULL)
❖ Step 7: Assign NULL to temp → previous → next and delete temp.
Deleting a Specific Node from the list
Deleting a Specific Node from the list
Step 1: Check whether list is Empty (head == NULL)
Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
Step 3: If it is not Empty, then define a Node pointer 'temp' and initialize with head.
Step 4: Keep moving the temp until it reaches to the exact node
to be deleted or to the last node.
Step 5: If it is reached to the last node, then display 'Given node not found in the list!
Deletion not possible!!!' and terminate the function.
Step 6: If it is reached to the exact node which we want to delete, then check whether list
is having only one node or not
Step 7: If list has only one node and that is the node which is to be deleted then set head
to NULL and delete temp (free(temp)).
Deleting a Specific Node from the list
Step 8: If list contains multiple nodes, then check whether temp is the first node in the
list (temp == head).
Step 9: If temp is the first node, then move the head to the next node (head = head →
next), set head of previous to NULL (head → previous = NULL) and delete temp.
Step 10: If temp is not the first node, then check whether it is the last node in the list
(temp → next == NULL).
Step 11: If temp is the last node then set temp of previous of next to NULL (temp→
previous → next = NULL) and delete temp(free(temp)).
Step 12: If temp is not the first node and not the last node, then
set temp of previous of next to temp of next (temp → previous → next = temp→ next),
temp of next of previous to temp of previous (temp → next → previous = temp →
previous) and delete temp (free(temp)).
Displaying a Double Linked List
Step 1: Check whether list is Empty (head == NULL)
Step 2: If it is Empty, then display 'List is Empty!!!' and terminate the
function.
Step 3: If it is not Empty, then define a Node pointer 'temp' and initialize
with head.
Step 4: Display 'NULL <--- '.
Step 5: Keep displaying temp → data with an arrow (<===>)
until temp reaches to the last node
Step 6: Finally, display temp → data with arrow pointing to NULL (temp → data --->
NULL).
Circular Linked List
❖ Circular linked list is a sequence of elements in which every element has link to its
next element in the sequence and the last element has a link to the first element in the
sequence.
Circular Linked List Operations
❖ In a circular linked list, we perform the following operations...

Insertion

Deletion

Display
Insertion Operations
❖ In a circular linked list, the insertion operation can be performed in three ways.
They are as follows...

Inserting At Beginning of the list

Inserting At End of the list

Inserting At Specific location in the list


Inserting At Beginning of the list
Inserting At Beginning of the list
Inserting At Beginning of the list
❖ Step 4: If it is Not Empty then, define a Node pointer 'temp' and initialize with
'head'.
❖ Step 5: Keep moving the 'temp' to its next node until it reaches to the last node
(until 'temp → next == head').
❖ Step 6: Set 'newNode → next =head', 'head = newNode' and 'temp → next =
head'.
Inserting At End of the list
Inserting At End of the list

Head=NULL

Head
Inserting At End of the list
❖ Step 4: If it is Not Empty then, define a node pointer temp and initialize
with head.
❖ Step 5: Keep moving the temp to its next node until it reaches to the last
node in the list (until temp → next == head).
❖ Step 6: Set temp → next = newNode and newNode → next = head.
Inserting At Specific location in the list
(After a Node)
Inserting At Specific location in the list
(After a Node)
❖ Step 1: Create a newNode with given value.
❖ Step 2: Check whether list is Empty (head == NULL)
❖ Step 3: If it is Empty then, set head = newNode and newNode → next = head.
❖ Step 4: If it is Not Empty then, define a node pointer temp and initialize with
head.
❖ Step 5: Keep moving the temp to its next node until it reaches to the node after
which we want to insert the newNode (until temp1 → data is equal to location,
here location is the node value after which we want to insert the newNode).
Inserting At Specific location in the list
(After a Node)
❖ Step 6: Every time check whether temp is reached to the last node or not. If it is
reached to last node then display 'Given node is not found in the list!!! Insertion
not possible!!!' and terminate the function. Otherwise move the temp to next
node.
❖ Step 7: If temp is reached to the exact node after which we want to insert the
newNode then check whether it is last node (temp → next== head).
❖ Step 8: If temp is last node then set temp → next = newNode and
newNode → next = head.
❖ Step 9: If temp is not last node then set newNode → next = temp → next and
temp → next = newNode.
Deletion
❖ In a circular linked list, the deletion operation can be performed in three
ways those are as follows...
Deleting from Beginning of the list
Deleting from End of the list
Deleting a Specific Node
Deleting from Beginning of the list
Deleting from Beginning of the list
❖ Step 1: Check whether list is Empty (head == NULL)
❖ Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
❖ Step 3: If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and
initialize both 'temp1' and 'temp2' with head.
❖ Step 4: Check whether list is having only one node (temp1 →next == head)
❖ Step 5: If it is TRUE then set head = NULL and delete temp1
(Setting Empty list conditions)
❖ Step 6: If it is FALSE move the temp1 until it reaches to the last node. (until
temp1 → next == head )
❖ Step 7: Then set head = temp2 → next, temp1 → next = head and
delete temp2.
Deleting from End of the list
Deleting from End of the list
❖ Step 1: Check whether list is Empty (head == NULL)
❖ Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
❖ Step 3: If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and
initialize 'temp1' with head.
❖ Step 4: Check whether list has only one Node (temp1 →next == head)
❖ Step 5: If it is TRUE. Then, set head = NULL and delete temp1. And terminate
from the function. (Setting Empty list condition)
❖ Step 6: If it is FALSE. Then set ‘temp2 = temp1’ and move temp1 to its next
node. Repeat the same until temp1 reaches to the last node in the list. (until temp1
→ next == head)
❖ Step 7: Set temp2 → next = head and delete temp1.
Deleting a Specific Node from the list
Deleting a Specific Node from the list
❖ Step 1: Check whether list is Empty (head == NULL)
❖ Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate
the function.
❖ Step 3: If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize
'temp1' with head.
❖ Step 4: Keep moving the temp1 until it reaches to the exact node to be deleted or to the
last node. And every time set 'temp2 = temp1' before moving the 'temp1' to its next node.
❖ Step 5: If it is reached to the last node then display 'Given node not found in the list!
Deletion not possible!!!'. And terminate the function.
❖ Step 6: If it is reached to the exact node which we want to delete, then check whether list
is having only one node (temp1 → next == head)
❖ Step 7: If list has only one node and that is the node to be deleted then set head = NULL
and delete temp1 (free(temp1)).
Deleting a Specific Node from the list
❖ Step 8: If list contains multiple nodes then check whether temp1 is the first node in the list
(temp1 == head).
❖ Step 9: If temp1 is the first node then set temp2 = head and keep moving temp2 to its next
node until temp2 reaches to the last node. Then set head = head → next, temp2 → next =
head and delete temp1.
❖ Step 10: If temp1 is not first node then check whether it is last node in the list (temp1 →
next == head).
❖ Step 11: If temp1 is last node then set temp2 → next = head and delete temp1
(free(temp1)).
❖ Step 12: If temp1 is not first node and not last node then set temp2 → next = temp1 →
next and delete temp1 (free(temp1)).
Displaying a circular Linked List
❖ Step 1: Check whether list is Empty (head == NULL)
❖ Step 2: If it is Empty, then display 'List is Empty!!!' and terminate the function.
❖ Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize with head.
❖ Step 4: Keep displaying temp → data with an arrow (--->) until temp reaches to the
last node
❖ Step 5: Finally display temp → data with arrow pointing to head → data.
Search & Join
Split
Linked List using Stack
Push(value) - Inserting an element into
the Stack
❖ Step 1: Create a newNode with given value.

❖ Step 2: Check whether stack is Empty (top == NULL)

❖ Step 3: If it is Empty, then set newNode → next = NULL.

❖ Step 4: If it is Not Empty, then set newNode → next = top.

❖ Step 5: Finally, set top = newNode.


Pop() - Deleting an Element from a
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)).


Display() - Displaying stack of elements

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

❖ Step 2: If it is Empty, then display 'Stack is Empty!!!' and terminate the function.

❖ Step 3: If it is Not Empty, then define a Node pointer 'temp' and initialize with top.

❖ Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same until
temp reaches to the first node in the stack (temp → next != NULL).

❖ Step 5: Finally! Display 'temp → data ---> NULL'.


Linked List using Stack
❖ The major problem with the queue implemented using array is, It will work for only
fixed number of data. That means, the amount of data must be specified in the
beginning itself. Queue using array is not suitable when we don't know the size of
data which we are going to use. A queue data structure can be implemented using
linked list data structure.
EnQueue(value) - Inserting an element
into the Queue
❖ Step 1: Create a newNode with given value and set 'newNode → next' to NULL.

❖ Step 2: Check whether queue is Empty (rear == NULL)

❖ Step 3: If it is Empty then,set front = newNode and rear = newNode.

❖ Step 4: If it is Not Empty then, set rear → next = newNode and rear = newNode.
DeQueue() - Deleting an Element from
Queue
❖ Step 1: Check whether queue is Empty (front == NULL).

❖ Step 2: If it is Empty, then display "Queue is Empty!!! Deletion is not


possible!!!" and terminate from the function

❖ Step 3: If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.

❖ Step 4: Then set 'front = front → next' and delete 'temp' (free(temp)).
Display() - Displaying the elements of
Queue
❖ Step 1: Check whether queue is Empty (front == NULL).

❖ Step 2: If it is Empty then, display 'Queue is Empty!!!' and terminate the function.

❖ Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize with front.

❖ Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same until
'temp' reaches to 'rear' (temp → next != NULL).

❖ Step 5: Finally! Display 'temp → data ---> NULL'.


Function : INSERT ( X, FIRST )
❖ This function inserts a new node at the first position of Singly linked list.
❖ This function returns address of FIRST node.
❖ X is a new element to be inserted.
❖ FIRST is a pointer to the first element of a Singly linked linear list.
❖ Typical node contains INFO and LINK fields.
❖ AVAIL is a pointer to the top element of the availability stack.
❖ NEW is a temporary pointer variable.
Function : INSERT ( X, FIRST )
Function : INSERT ( X, FIRST )
Function : INSEND ( X, LAST )
❖ This function inserts a new node at the last position of linked list.
❖ This function returns address of FIRST node.
❖ X is a new element to be inserted.
❖ FIRST is a pointer to the first element of a Singly linked linear list.
❖ Typical node contains INFO and LINK fields.
❖ AVAIL is a pointer to the top element of the availability stack.
❖ NEW is a temporary pointer variable.
Function : INSEND ( X, LAST )
Function : INSEND ( X, LAST )
Function : INSORD ( X, FIRST )
Function : INSORD ( X, FIRST )
Function : INSORD ( X, FIRST )
Function : INSORD ( X, FIRST )
Procedure : DELETE ( X, FIRST )
Procedure : DELETE ( X, FIRST )
Procedure : DELETE ( X, FIRST )
Function : COUNT ( FIRST )
Function : COPY ( FIRST )
❖ This function Copy a Link List and creates new Linked List
❖ This function returns address of first node of newly created linked list.
❖ The new list is to contain nodes whose information and pointer fields are denoted by
FIELD and PTR, respectively.
❖ The address of the first node in the newly created list is to be placed in BEGIN
❖ FIRST is a pointer to the first element of a Singly linked linear list.
❖ Typical node contains INFO and LINK fields.
❖ AVAIL is a pointer to the top element of the availability stack.
❖ NEW, SAVE and PRED are temporary pointer variables.
Function : COPY ( FIRST )
Function : COPY ( FIRST )
Function : COPY ( FIRST )
Application of Link List
❖ Implementation of stacks and queues
❖ Implementation of graphs: Adjacency list representation of graphs is the most popular
which uses a linked list to store adjacent vertices.
❖ Dynamic memory allocation: We use a linked list of free blocks.
❖ Maintaining a directory of names
❖ Performing arithmetic operations on long integers
❖ Manipulation of polynomials by storing constants in the node of the linked list
❖ Representing sparse matrices
Applications of linked list in the real
world:
❖ Image viewer :-Previous and next images are linked and can be accessed by the next and
previous buttons.
❖ Previous and next page in a web browser:-We can access the previous and next URL
searched in a web browser by pressing the back and next buttons since they are linked as a
linked list.
❖ Music Player:-Songs in the music player are linked to the previous and next songs. So
you can play songs either from starting or ending of the list.
❖ GPS navigation systems:- Linked lists can be used to store and manage a list of locations
and routes, allowing users to easily navigate to their desired destination.
❖ Robotics:- Linked lists can be used to implement control systems for robots, allowing
them to navigate and interact with their environment.
Applications of linked list in the real
world:
❖ Task Scheduling:- Operating systems use linked lists to manage task scheduling, where
each process waiting to be executed is represented as a node in the list.
❖ Image Processing:- Linked lists can be used to represent images, where each pixel is
represented as a node in the list.
❖ File Systems:- File systems use linked lists to represent the hierarchical structure of
directories, where each directory or file is represented as a node in the list.
❖ Symbol Table:- Compilers use linked lists to build a symbol table, which is a data
structure that stores information about identifiers used in a program.
❖ Undo/Redo Functionality:- Many software applications implement undo/redo
functionality using linked lists, where each action that can be undone is represented as a
node in a doubly linked list.
Applications of linked list in the real
world:
❖ Speech Recognition:- Speech recognition software uses linked lists to represent the
possible phonetic pronunciations of a word, where each possible pronunciation is
represented as a node in the list.
❖ Polynomial Representation:- Polynomials can be represented using linked lists, where
each term in the polynomial is represented as a node in the list.
❖ Simulation of Physical Systems:- Linked lists can be used to simulate physical systems,
where each element in the list represents a discrete point in time and the state of the
system at that time.
Applications of Circular Linked Lists:
❖ Useful for implementation of a queue. Unlike this implementation, we don’t need to
maintain two-pointers for the front and rear if we use a circular linked list. We can maintain
a pointer to the last inserted node and the front can always be obtained as next of last.
❖ Circular lists are useful in applications to go around the list repeatedly. For example, when
multiple applications are running on a PC, it is common for the operating system to put the
running applications on a list and then cycle through them, giving each of them a slice of
time to execute, and then making them wait while the CPU is given to another application.
It is convenient for the operating system to use a circular list so that when it reaches the end
of the list it can cycle around to the front of the list.
❖ Circular Doubly Linked Lists are used for the implementation of advanced data structures
like the Fibonacci Heap.
❖ Circular linked lists can be used to implement circular queues, which are often used in
operating systems for scheduling processes and managing memory allocation.
Applications of Circular Linked Lists:
❖ Used in database systems to implement linked data structures, such as B+ trees, which are
used to optimize the storage and retrieval of data.
❖ Circular linked lists can be used in networking. For instance, to implement circular buffers
for streaming data, such as video and audio, in networking applications.
❖ Video games use circular linked lists to manage sprite animations. Each frame of the
animation is represented as a node in the list, and the last frame is connected to the first
frame to create a loop.
❖ Circular linked lists can be used to represent a buffer of audio or signal data in signal
processing applications. The last node is connected to the first node to create a loop, and
the processing algorithms can efficiently iterate over the data.
❖ Traffic light control systems use circular linked lists to manage the traffic light cycles.
Each phase of the traffic light cycle is represented as a node in the list, and the last node is
connected to the first node to create a loop.
Applications of Doubly Linked Lists:
❖ Redo and undo functionality.
❖ Use of the Back and forward button in a browser.
❖ The most recently used section is represented by the Doubly Linked list.
❖ Other Data structures like Stack, Hash Table, and Binary Tree can also be applied by
Doubly Linked List.
❖ Used to implement game objects and their interactions in a game engine.
❖ Used in networking.
❖ Used in Graph algorithms.
❖ Operating systems use doubly linked lists to manage the process scheduling. Each process
waiting to be executed is represented as a node in the doubly linked list, and the operating
system can easily traverse the list in both directions to manage the process queue.
Thank You

You might also like