You are on page 1of 64

Lecture Notes|| Unit -1

CO1: Implement arrays and memory allocation strategies.

Syllabus: Revision of Function and Structure, Revision of concept of types of pointers and its applications,
Memory Allocation- Static and Dynamic. Introduction: Basic Terminology, Elementary Data Organization,
Arrays: Definition, Single and Multidimensional Arrays, Representation of Arrays: Row Major Order, and
Column Major Order, Application of arrays, Sparse Matrices and their representations.

[T-1] Prerequisites of Subject [Function]

function & 3. Type of value return by the function


Function: - Syntax:
• Definition: A function is a group of statements that return type function name (type1 arg1 , type2 arg2);
together perform a task. Every C program has at least one
function, which is main (), and all the most trivial •Function Definition: It consists of code description
programs can define additional functions.
and code of a function. It consists of two parts 1.
Function header 2. Function coding
• Monolithic Vs Modular Programming-Monolithic
Programming indicates the program which contains a Function definition tells what the I/O functions are and
single function for the large program. Modular what is going to do.
programming helps the programmer to divide the whole Syntax:
program into different Units and each Unit is separately return type function name (type1 arg1 , type2 arg2)
developed and tested. {
local variable;
• Disadvantages of monolithic programming: statements;
1. Difficult to check error on large programs. 2. Difficult return (expression);
to maintain. 3. Code can be specific to a particular }
problem. i.e. it cannot be reused.
Function Categories- There are four main categories
• Advantage of modular programming: 1. Modular of the functions these are as follows:
program are easier to code and debug. 2. Reduces the 1. Function with no arguments and no return values.
programming size. 3. Code can be reused in other 2. Function with no arguments and a return value.
programs. 4. Problem can be isolated to specific Unit so 3. Function with arguments and no return values.
easier to find the error and correct it. 4. Function with arguments and return values.

• A function that is designed for user specific task is Actual Arguments: Arguments which are mentioned
called user defined function. Every user define function in the function call.
has three parts as: Prototype or Declaration, Calling, Formal Arguments: Arguments which are mentioned
Definition in function definition are called dummy or formal
argument. These arguments are used to just hold the
• Function Declaration OR Function Prototype: It is
value that is sent by calling function. Formal arguments
also known as function prototype. It informs the
are like other local variables of the function which are
computer about the three things 1. Name of the function
created when function call starts and destroyed when
2. Number and type of arguments received by the
end function.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 4
Parameter passing methods-
There are two ways to pass value or data to function in C language which is given below;
• call by value
• call by reference

Example of a Call by Value method Example of a Call by Value method


#include<stdio.h> #include<stdio.h>
void increment(int); void increment(int *x);
void main() void main()
{ {
int a = 10; int a = 10;
printf("Before function calling: %d", a); printf("Before function calling: %d", a);
increment(a); increment(&a);
printf("After function calling: %d", a); printf("After function calling: %d", a);
getch(); getch();
} }
void increment(int x) void increment(int *x)
{ {
x = x + 1; *x = *x + 1;
printf ("In function value is: %d", x); printf ("In function value is:", *x);
} }
Output: Output:
Before function calling 10 Before function calling 10
In function value is 11 In function value is 11
After function calling 10 After function calling 11

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 5
Passing Array to a function:

**Passing individual array elements to a function


Passing values of individual array elements to a function (CBV)

Passing addresses of individual array elements to a function (CBR)

**How to pass an entire array to a function as an argument?


Passing entire array to a function (CBV)

Passing entire array to a function (CBR)

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 6
• Recursion: When a function calls itself then that int sum(int n)
function is called Recursive function. { if (n != 0)
return n + sum(n-1); // sum()
void recurse() function calls itself
{ recurse();
else
}
int main() return n;
{ recurse(); }
}
Output
Example: Sum of Natural Numbers Using Enter a positive integer:3
Recursion sum = 6
#include <stdio.h>
int sum(int n);
int main() • Advantage of Recursion
{ a) Function calling related information will be
int number, result; maintained by recursion.
printf("Enter a positive integer: "); b) Stack evaluation will be take place by using
recursion.
scanf("%d", &number);
c) In fix prefix, post-fix notation will be
result = sum(number); evaluated by using recursion.
printf("sum = %d", result);
return 0; • Disadvantage of Recursion
} 1. It is a very slow process due to stack
overlapping.
2. Recursive programs can create stack
overflow.
3. Recursive functions can create as loops.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 7
[T-2] Prerequisites of Subject [Structure]

• Structure: A Structure is a user defined data type • Example:


that can store related information together.
Structures are used to represent a record.
// C program to demonstrate structure pointer
• Structure Declaration-It is declared using a #include <stdio.h>
keyword struct followed by the name of the structure. struct point
The variables of the structure are declared within the {
structure. int value;
Example: };
Struct struct-name
{ int main()
data_type var-name; { struct point s;
data_type var-name; struct point* ptr = &s;
}; // Initialization of the structure pointer
return 0;
}
• Structure Initialization-Assigning constants to
the members of the structure is called initializing In the above code s is an instance of struct point
of structure.Syntax: and ptr is the struct pointer because it is storing the
struct struct_name address of struct point.
{data _type member_name1; • Accessing the Structure Member with the Help
data _type member_name2; of Pointers
} struct_var= {constant1, constant2}; There are two ways to access the members
of the structure with the help of a structure
• Accessing the Members of a structure-A structure pointer:
member variable is generally accessed using a ‘.’ 1.With the help of (*) asterisk or indirection
operator.
operator and (.) dot operator.
Syntax: strcut_var. member_name;
The dot operator is used to select a particular member 2.With the help of ( -> ) Arrow operator.
of the structure.
To input values for data members of the structure #include <stdio.h>
variable stud, can be written as, struct person
scanf(“%d”,&stud.roll); {
scanf(‘’%s”,&stud.name); int age;
To print the values of structure variable stud, can be
written as: float weight;
printf(“%s”,stud.roll); };
printf(“%f”, stud.name); int main()
{ struct person *personPtr, person1;
• Structure Pointer in C:A structure pointer is defined personPtr = &person1;
as the pointer which points to the address of the printf("Enter age: ");
memory block that stores a structure known as the scanf("%d", &personPtr->age);
structure pointer. Complex data structures like linked printf("Enter weight: ");
lists, trees, graphs, etc. are created with the help of scanf("%f", &personPtr->weight);
structure pointers. The structure pointer tells the printf("Displaying:\n");
address of a structure in memory by pointing the printf("Age: %d\n", personPtr->age);
variable to the structure variable. printf("weight: %f", personPtr-weight);
return 0;
}

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 8
In this example, the address of person1 is Output
stored in the personPtr pointer Name : Tata
using personPtr = &person1; Now, you Price : 1021
can access the members of person1 using
Example 2: Using Call By Reference
the personPtr pointer. Method
By the way,
personPtr->age is equivalent // C program to pass structure as an argument to
to (*personPtr).age the functions using Call By Reference
personPtr->weight is equivalent Method
#include <stdio.h>
to (*personPtr).weight
struct student {
char name[50];
int roll;
How to Pass or Return a Structure To or From a float marks;
Function in C? };
void display(struct student* student_obj)
Example 1: Using Call By Value Method {
printf("Name: %s\n", student_obj->name);
printf("Roll: %d\n", student_obj->roll);
// C program to pass structure as an printf("Marks: %f\n", student_obj->marks);
argument to the functions using Call By }
Value Method int main()
{ struct student st1 = { "Aman", 19, 8.5 };
#include <stdio.h> display(&st1);
struct car return 0;
{ }
char name[30];
int price; Output
}; Name: Aman
Roll: 19
void print_car_info(struct car c) Marks: 8.500000
{
printf("Name : %s", c.name);
printf("\nPrice : %d\n", c.price);
}

int main()
{
struct car c = { "Tata", 1021 };
print_car_info(c);
return 0;
}

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 9
[T-3] Pointers and its applications (DMA)

• Every variable in C has a name and a value associated with it. When a variable is declared, a specific block of
memory within the computer is allocated to hold the value of that variable.
Consider the declaration, int i = 3 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.
We may represent i’s location in memory by the following memory map.

• We see that the computer has selected memory location 65524 as the place to store the value 3. The location
number 65524 is not a number to be relied upon, because some other time the computer may choose a
different location for storing the value 3. The important point is, i’s address in memory is a number.
• A pointer is a variable that contains the memory location of another variable.
• Pointers applications include:
a) Pointers are used to pass information back and forth between functions.
b) Pointers enable the programmers to return multiple data items from a function via function arguments.
c) Pointers provide an alternate way to access the individual elements of an array.
d) Pointers are used to pass arrays and strings as function arguments.
e) Pointers are used to create complex data structures, such as trees, linked lists, linked stacks, linked
queues, and graphs.
f) Pointers are used for the dynamic memory allocation of a variable
• The general syntax of declaring pointer variables can be given as below.
data_type *ptr_name;
• Now we can say—pointers are variables that contain addresses, and since addresses are always whole
numbers, pointers would always contain whole numbers.
• Every time a pointer is incremented it points to the immediately next location of its type.
• Thus, the following operations can be performed on a pointer:
(a) Addition of a number to a pointer. For example,
int i = 4, *j, *k ; j = &i ; j = j + 1 ; j = j + 9 ; k = j + 3 ;
(b) Subtraction of a number from a pointer. For example,
j = &i ; j = j - 2 ; j = j - 5 ; k = j - 6 ;
(c) Subtraction of one pointer from another.
One pointer variable can be subtracted from another provided both variables point to elements of the same
array.
(d) Comparison of two pointer variables
Pointer variables can be compared provided both variables point to objects of the same data type. Such
comparisons can be useful when both pointer variables point to elements of the same array.
• **A word of caution! Do not attempt the following operations on pointers... they would never work out.
(a) Addition of two pointers
(b) Multiplication of a pointer with a constant
(c) Division of a pointer with a constant

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 10
Memory Allocation- Static and Dynamic
• Dynamic memory management refers to manual memory management. This allows you to obtain more
memory when required and release it when not necessary.
• Although C inherently does not have any technique to allocate memory dynamically, there are 4 library
functions defined under <stdlib.h> for dynamic memory allocation.

• malloc()
The name malloc stands for "memory allocation".The function malloc() reserves a block of memory of
specified size and return a pointer of type void which can be casted into pointer of any form.
Syntax of malloc()➔ ptr = (cast-type*) malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of
byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.

• calloc()
The name calloc stands for "contiguous allocation".The only difference between malloc() and calloc() is
that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory
each of same size and sets all bytes to zero.
Syntax of calloc()➔ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e,
4 bytes.

• free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own. You
must explicitly use free() to release the space.
syntax of free()➔free(ptr); //This statement frees the space allocated in the memory pointed by ptr.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 11
Example #1: Using C malloc() and free() printf("Enter elements of array: ");
Write a C program to find sum of n elements entered for(i = 0; i < num; ++i)
by user. To perform this program, allocate memory {
dynamically using malloc() function. scanf("%d", ptr + i);
#include <stdio.h> sum += *(ptr + i);
#include <stdlib.h> }
int main() printf("Sum = %d", sum);
{ int num, i, *ptr, sum = 0; free(ptr);
printf("Enter number of elements: "); return 0;
scanf("%d", &num); }
ptr = (int*) malloc(num * sizeof(int)); //memory
allocated using malloc • realloc()
if(ptr == NULL) If the previously allocated memory is
{ printf("Error! memory not allocated."); insufficient or more than required, you can
exit(0); change the previously allocated memory size
} using realloc().
printf("Enter elements of array: "); Syntax of realloc() ➔ptr = realloc(ptr,
for(i = 0; i < num; ++i) newsize);
{ scanf("%d", ptr + i); Here, ptr is reallocated with size of newsize.
sum += *(ptr + i);
} Example #3: Using realloc()
printf("Sum = %d", sum); #include <stdio.h>
free(ptr); #include <stdlib.h>
return 0; int main()
} {
int *ptr, i , n1, n2;
Example #2: Using C calloc() and free() printf("Enter size of array: ");
Write a C program to find sum of n elements entered scanf("%d", &n1);
by user. To perform this program, allocate memory ptr = (int*) malloc(n1 * sizeof(int));
dynamically using calloc() function. printf("Address of previously allocated memory:
#include <stdio.h> ");
#include <stdlib.h> for(i = 0; i < n1; ++i)
int main() printf("%u\t",ptr + i);
{ printf("\nEnter new size of array: ");
int num, i, *ptr, sum = 0; scanf("%d", &n2);
printf("Enter number of elements: "); ptr = realloc(ptr, n2 * sizeof(int));
scanf("%d", &num); for(i = 0; i < n2; ++i)
ptr = (int*) calloc(num, sizeof(int)); printf("%u\t", ptr + i);
if(ptr == NULL) return 0;
{ }
printf("Error! memory not allocated.");
exit(0);
}

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 12
[T-4] Introduction: Basic Terminology, Elementary Data Organization

• A good program is defined as a program that runs correctly, easy to read and understand, easy to debug and
easy to modify.
• A program is said to be efficient when it executes in minimum time and with minimum memory space.
• In order to write efficient programs, we need to apply certain data management concepts.
• Data structure is a crucial part of data management.
• A data structure is basically a group of data elements that are put together under one name, and which defines
a particular way of storing and organizing data in a computer so that it can be used efficiently.
• Data: Data are simply values or sets of values.
• Data items: Data items refers to a single unit of values. Data items that are divided into sub-items are called
Group items. Ex: An Employee Name may be divided into three subitems- first name, middle name, and last
name.
• Data items that are not able to divide into sub-items are called Elementary items. Ex: SSN
• Entity: An entity is something that has certain attributes or properties which may be assigned values. The
values may be either numeric or non-numeric. Ex: Attributes- Names, Age, Sex, SSN Values- Rohland Gail,
34, F, 134-34-5533 Entities with similar attributes form an entity set. Each attribute of an entity set has a
range of values, the set of all possible values that could be assigned to the particular attribute.
• The term “information” is sometimes used for data with given attributes, of, in other words meaningful or
processed data.
• Field is a single elementary unit of information representing an attribute of an entity.
• Record is the collection of field values of a given entity.
• File is the collection of records of the entities in a given entity set.
• Each record in a file may contain many field items but the value in a certain field may uniquely determine
the record in the file. Such a field K is called a primary key.
• Records may also be classified according to length. A file can have fixed-length records or variable-length
records.
• In fixed-length records, all the records contain the same data items with the same amount of space assigned
to each data item.
• In variable-length records file records may contain different lengths. Example: Student records have
variable lengths, since different students take different numbers of courses. Variable-length records have a
minimum and a maximum length.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 13
What do you mean by the term “Data Structure”?
• Organizing the data in memory.
• A data structure is a way of organizing the data so that it can be used efficiently. Here, we have used the
word efficiently, which in terms of both the space and time.
• It is a set of algorithms that we can use in any programming language to structure the data in the memory.

Classification of Data Structure:

• Linear data structure:


Data structure in which data elements are arranged sequentially or linearly, where each element is attached to its
previous and next adjacent elements, is called a linear data structure. Examples of linear data structures are array,
stack, queue, linked list, etc.

Static data structure: Static data structure has a fixed memory size. It is easier to access the elements in a static
data structure. An example of this data structure is an array.

Dynamic data structure: In dynamic data structure, the size is not fixed. It can be randomly updated during the
runtime which may be considered efficient concerning the memory (space) complexity of the code. Examples of
this data structure are queue, stack, etc.

• Non-linear data structure:


Data structures where data elements are not placed sequentially or linearly are called non-linear data structures. In
a non-linear data structure, we can’t traverse all the elements in a single run only. Examples of non-linear data
structures are trees and graphs.

• The major or the common operations that can be performed on the data structures are:
o Searching: We can search for any element in a data structure.
o Sorting: We can sort the elements of a data structure either in an ascending or descending order.
o Insertion: We can also insert the new element in a data structure.
o Updation: We can also update the element, i.e., we can replace the element with another element.
o Deletion: We can also perform the delete operation to remove the element from the data structure.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 14
• Advantages of Data structures
The following are the advantages of a data structure:
o Efficiency: If the choice of a data structure for implementing a particular ADT is proper, it makes the
program very efficient in terms of time and space.
o Reusability: The data structure provides reusability means that multiple client programs can use the data
structure.
o Abstraction: The data structure specified by an ADT also provides the level of abstraction. The client cannot
see the internal working of the data structure, so it does not have to worry about the implementation part.
The client can only see the interface.

• An abstract data type (ADT) is the way we look at a data structure, focusing on what it does and ignoring how
it does its job. For example, stacks and queues are perfect examples of an ADT. We can implement both these
ADTs using an array or a linked list. This demonstrates the ‘abstract’ nature of stacks and queues.They are not
concerned about how they work.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 15
[T-5] Arrays: Definition, Declaration, Initialization & Processing of Single and Multidimensional Arrays

Array Data Structure


Definition
• An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items
of the same type together.
• They exist in both single dimension and multiple dimensions.
Basic terminologies of the array:
• Array Index: In an array, elements are identified by their indexes. Array index starts from 0.
• Array element: Elements are items stored in an array and can be accessed by their index.
• Array Length: The length of an array is determined by the number of elements it can contain.

Syntax
Creating an array in C language –Arrays are declared using the following syntax:
type name[size];
For example, if we write,
int marks[10];
In the memory, the array will be stored as shown
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
element element element element element element element element element element
marks [0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7] marks[8] marks[9]

Types of arrays:
There are following types of arrays:
• One-dimensional array (1-D arrays): You can imagine a 1d array as a row, where elements are stored one
after another.

1D array
• Two-dimensional array: 2-D Multidimensional arrays can be considered as an array of arrays or as a matrix
consisting of rows and columns.

2D array
• Three-dimensional array: A 3-D Multidimensional array contains three dimensions, so it can be considered
an array of two-dimensional arrays.

3D array

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 16
Declaration, Initialization & Processing of Single and Multidimensional Arrays
One Dimensional Array

Declaration:
Syntax: ➔data_type array_name[size];
data_type represents the type of elements present in the array. array_name represents the name of the array.
Size represents the number of elements that can be stored in the array.
Example:➔int age[100]; float sal[15]; char grade[20];
Here age is an integer type array, which can store 100 elements of integer type. The array sal is floating type array
of size 15, can hold float values. Grade is a character type array which holds 20 characters.

Initialization:
Syntax: ➔data_type array_name[size]={value1, value2,……..valueN};
Value1, value2, valueN are the constant values known as initializers, which are assigned to the array elements one
after another.
Example: ➔int marks[5]={10,2,0,23,4};
The values of the array elements after this initialization are: marks[0]=10, marks[1]=2, marks[2]=0, marks[3]=23,
marks[4]=4

Note-:
In 1-D arrays it is optional to specify the size of the array. If size is omitted during initialization, then the
compiler assumes the size of array equal to the number of initializers. Example:int marks []={10,2,0,23,4};Here
the size of array marks is initialized to 5.
We can’t copy the elements of one array to another array by simply assigning it. Example:
int a[5]={9,8,7,6,5}; int b[5];
b=a; //not valid
we have to copy all the elements by using for loop.
for(a=i; i<5; i++) b[i]=a[i];

Processing:
For processing arrays we mostly use for loop. The total no. of passes is equal to the no. of elements present in the
array and in each pass one element is processed.
Example:
#include<stdio.h>
main()
{
int a[3],i;
for(i=0;i<=2;i++) //Reading the array values
{
printf(“enter the elements”);
scanf(“%d”,&a[i]);
}
for(i=0;i<=2;i++) //display the array values
{ printf(“%d”,a[i]);
printf(“\n”);
}
}

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 17
Two Dimensional Arrays-
Arrays that we have considered up to now are one dimensional array, a single line of elements. Often data come
naturally in the form of a table, e.g. spreadsheet, which need a two-dimensional array.

Declaration:
Syntax: ➔data_type array_name[rowsize][columnsize];
Rowsize specifies the no.of rows ,Columnsize specifies the no.of columns.
Example: ➔int a[4][5];
This is a 2-D array of 4 rows and 5 columns. Here the first element of the array is a[0][0] and last element of the
array is a[3][4] and total no.of elements is 4*5=20.

Initialization:
2-D arrays can be initialized in a way similar to 1-D arrays.
Example: ➔int m[4][3]={1,2,3,4,5,6,7,8,9,10,11,12};

Note:
In 2-D arrays it is optional to specify the first dimension but the second dimension should always be present.
Example: int m[][3]={
{1,10},
{2,20,200},
{3}, {4,40,400} };
Here the first dimension is taken 4 since there are 4 roes in the initialization list. A 2-D array is known as matrix.

Processing:
For processing of 2-D arrays we need two nested for loops. The outer loop indicates the rows and the inner loop
indicates the columns.
Example: ➔
int a[4][5];
Reading values in a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
scanf(“%d”,&a[i][j]);
Displaying values of a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
printf(“%d”,a[i][j]);
This program reads and displays 3 elements of integer type.

Declaration of Three-Dimensional Array:


We can declare a 3D array with x 2D arrays each having y rows and z columns using the syntax shown below.
Syntax:➔
data_type array_name[x][y][z];
• data_type: Type of data to be stored in each element.
• array_name: name of the array
• x: Number of 2D arrays.
• y: Number of rows in each 2D array.
• z: Number of columns in each 2D array.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 18
Representation of Arrays: Row Major Order, and Column Major Order

• When it comes to organizing and accessing elements in a multi-dimensional array, two prevalent methods
are Row Major Order and Column Major Order.

• These approaches define how elements are stored in memory and impact the efficiency of data access in
computing.

Row Major Order


Row major ordering assigns successive elements, moving across the rows and then down the next row, to
successive memory locations. In simple language, the elements of an array are stored in a Row-Wise fashion.

To find the address of the element using row-major order uses the following formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in an array(in byte),
LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of the matrix(If not given assume it as zero),
N = Number of column given in the matrix.

How to find address using Row Major Order?

Q-Given an array, arr[1………10][1………15] with base value 100 and the size of each element is 1 Byte in
memory. Find the address of arr[8][6] with the help of row-major order.
Solution:Given: Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of column given in the matrix N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1
= 15
Formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))

Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1))


= 100 + 1 * ((7) * 15 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 19
Column Major Order
If elements of an array are stored in a column-major fashion means moving across the column and then to the next
column then it’s in column-major order.

To find the address of the element using column-major order use the following formula:
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LR = Lower Limit of row/start row index of matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of matrix(If not given assume it as zero),
M = Number of rows given in the matrix.

How to find address using Column Major Order?


Q-Given an array arr[1………10][1………15] with a base value of 100 and the size of each element is 1 Byte in
memory find the address of arr[8][6] with the help of column-major order.
Solution:Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of Rows given in the matrix M = Upper Bound – Lower Bound + 1
= 10 – 1 + 1
= 10
Formula: used
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
Address of A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1))
= 100 + 1 * ((5) * 10 + (7))
= 100 + 1 * (57)
Address of A[I][J] = 157

To find the address of any element in 3-Dimensional arrays there are the following two ways:
• Row Major Order
• Column Major Order

Row Major Order:


To find the address of the element using row-major order, use the following formula:
Address of A[i][j][k] = B + W *(M * N * (i-x) + N *(j-y) + (k-z))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of Row
y = Lower Bound of Column
z = Lower Bound of Width

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 20
Example: Given an array, arr[1:9, -4:1, 5:10] with a base value of 400 and the size of each element is 2
Bytes in memory find the address of element arr[5][-1][8] with the help of row-major order?
Solution:
Given:
Block Subset of an element whose address to be found I = 5
Row Subset of an element whose address to be found J = -1
Column Subset of an element whose address to be found K = 8
Base address B = 400
Storage size of one element store in any array(in Byte) W = 2
Lower Limit of blocks in matrix x = 1
Lower Limit of row/start row index of matrix y = -4
Lower Limit of column/start column index of matrix z = 5
M(row) = Upper Bound – Lower Bound + 1 = 1 – (-4) + 1 = 6
N(Column)= Upper Bound – Lower Bound + 1 = 10 – 5 + 1 = 6

Formula used:
Address of[I][J][K] =B + W (M * N(i-x) + N *(j-y) + (k-z))

Address of arr[5][-1][8] = 400 + 2 * {[6 * 6 * (5 – 1)] + 6 * [(-1 + 4)]} + [8 – 5]


= 400 + 2 * (6*6*4)+(6*3)+3
= 400 + 2 * (165)
= 730

Column Major Order:


To find the address of the element using column-major order, use the following formula:1
Address of A[i][j][k]= B + W(M * N(i – x) + M *(k – z) + (j – y))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of block (first subscipt)
y = Lower Bound of Row
z = Lower Bound of Column

Example: Given an array arr[1:8, -5:5, -10:5] with a base value of 400 and the size of each element is 4
Bytes in memory find the address of element arr[3][3][3] with the help of column-major order ?
Solution:
Given:
Row Subset of an element whose address to be found I = 3
Column Subset of an element whose address to be found J = 3
Block Subset of an element whose address to be found K = 3
Base address B = 400
Storage size of one element store in any array(in Byte) W = 4
Lower Limit of blocks in matrix x = 1
Lower Limit of row/start row index of matrix y = -5
Lower Limit of column/start column index of matrix z = -10
M (row)= Upper Bound – Lower Bound + 1 = 5 +5 + 1 = 11
N (column)= Upper Bound – Lower Bound + 1 = 5 + 10 + 1 = 16
Formula used:
Address of[i][j][k] = B + W(M * N(i – x) + M * (j-y) + (k – z))

Address of arr[3][3][3] = 400 + 4 * ((11*16*(3-1)+11*(3-(-5)+(3-(-10)))

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 21
= 400 + 4 * ((176*2 + 11*8 + 13)
= 400 + 4 * (453)
= 400 + 1812
= 2212

Operations supported by an array.


2. Insertion
1. Traverse and display Write a program to insert a number at a given
Write a program to read and display n numbers location in an array.
using an array. #include <stdio.h>
int main()
#include <stdio.h> {
#include <conio.h> int i, n, num, pos, arr[10];
int main() clrscr();
{ printf("\n Enter the no of elements in the array : ");
int i, n, arr[20]; scanf("%d", &n);
clrscr(); for(i=0;i<n;i++)
printf("\n Enter the no of elements in the array : "); {
scanf("%d", &n); printf("\n arr[%d] = ", i);
for(i=0;i<n;i++) scanf("%d", &arr[i]);
{ }
printf("\n arr[%d] = ", i); printf("\n Enter the number to be inserted : ");
scanf("%d",&arr[i]); scanf("%d", &num);
} printf("\n Enter the position at which the number has
printf("\n The array elements are "); to be added : ");
for(i=0;i<n;i++) scanf("%d", &pos);
printf("\t %d", arr[i]); for(i=n–1;i>=pos;i––)
return 0; arr[i+1] = arr[i];
} arr[pos] = num;
Output n = n+1;
Enter the number of elements in the array : 5 printf("\n The array after insertion of %d is : ",
arr[0] = 1 num);
arr[1] = 2 for(i=0;i<n;i++)
arr[2] = 3 printf("\n arr[%d] = %d", i, arr[i]);
arr[3] = 4 return 0;
arr[4] = 5 }
Output
The array elements are 1 2 3 4 5 Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
Enter the number to be inserted : 0
Enter the position at which the number has to be
added : 3
The array after insertion of 0 is :
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 0
arr[4] = 4
arr[5] = 5

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 22
4.Search &Update
3.Deletion #include<stdio.h>
Write a program to delete a number from a given int main()
location in an array. { int i,t,a[10],n,m,s,j=0,b[10];
printf("\nEnter the Limit:");
#include <stdio.h> scanf("%d",&n);
int main() printf("\nEnter the Values:");
{ for(i=0i<n;i++)
int i, n, pos, arr[10]; { scanf("%d",&a[i]);
clrscr(); }
printf("\n Enter the no of elements in the array : "); printf("\nGiven values are:");
scanf("%d", &n); for(i=0;i<n;i++)
for(i=0;i<n;i++) { printf("a[%d]=%d",i,a[i]);
{ }
printf("\n arr[%d] = ", i); printf("\nEnter the position to be update:");
scanf("%d", &arr[i]); scanf("%d",&t);
} printf("\nEnter the value to be update:");
printf("\nEnter the position from which the number scanf("%d",&s);
has to be deleted : "); for(i=0;i<n;i++)
scanf("%d", &pos); {
for(i=pos; i<n–1;i++) if(i==t)
arr[i] = arr[i+1]; { a[i]=s;
n– –; }
printf("\n The array after deletion is : "); }
for(i=0;i<n;i++) printf("\nUpdated value is:");
printf("\n arr[%d] = %d", i, arr[i]); for(i=0;i<n;i++)
return 0; { printf("\na[%d]=%d",i,a[i]);
} }
Output return 0;
Enter the number of elements in the array : 5 }
arr[0] = 1 Output
arr[1] = 2 Enter the limit:5
arr[2] = 3 Enter the values:1 2 3 4 5
arr[3] = 4 Given values are:
arr[4] = 5 a[0]=1
Enter the position from which the number has to be a[1]=2
deleted : 3 a[2]=3
The array after deletion is : a[3]=4
arr[0] = 1 a[4]=5
arr[1] = 2 Enter the position to be update:3
arr[2] = 3 Enter the value to be update:5
arr[3] = 5 Inserted value is:
a[0]=1
a[1]=2
a[2]=3
a[3]=5
a[4]=4
a[5]=5

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 23
2. Write a program to input two m x n matrices
Basic Operations on 2D array: and then calculate the sum of their corresponding
elements and store it in a third m x n matrix.
1.Write a program to transpose a 3 x 3 matrix. #include <stdio.h>
int main()
#include <stdio.h> {
int main() int i, j;
{ int rows1, cols1, rows2, cols2, rows_sum, cols_sum;
int i, j, mat[3][3], transposed_mat[3][3]; int mat1[5][5], mat2[5][5], sum[5][5];
clrscr(); clrscr();
printf("\n Enter the elements of the matrix "); printf("\n Enter the number of rows in the first
for(i=0;i<3;i++) matrix : ");
{ scanf("%d",&rows1);
for(j=0;j<3;j++) printf("\n Enter the number of columns in the first
{ matrix : ");
scanf("%d", &mat[i][j]); scanf("%d",&cols1);
} printf("\n Enter the number of rows in the second
} matrix : ");
printf("\n The elements of the matrix are "); scanf("%d",&rows2);
for(i=0;i<3;i++) printf("\n Enter the number of columns in the second
{ matrix : ");
printf("\n"); scanf("%d",&cols2);
for(j=0;j<3;j++) if(rows1 != rows2 || cols1 != cols2)
printf("\t %d", mat[i][j]); {
} printf("\n Number of rows and columns of both
for(i=0;i<3;i++) matrices must be equal");
{ exit(0);
for(j=0;j<3;j++) }
transposed_mat[i][j] = mat[j][i]; rows_sum = rows1;
} cols_sum = cols1;
printf("\n The elements of the transposed matrix are printf("\n Enter the elements of the first matrix ");
"); for(i=0;i<rows1;i++)
for(i=0;i<3;i++) {
{ for(j=0;j<cols1;j++)
printf("\n"); {
for(j=0;j<3;j++) scanf("%d",&mat1[i][j]);
printf("\t %d",transposed_ mat[i][j]);} }
return 0; }
} printf("\n Enter the elements of the second matrix ");
Output for(i=0;i<rows2;i++)
Enter the elements of the matrix {
123456789 for(j=0;j<cols2;j++)
The elements of the matrix are {
123 scanf("%d",&mat2[i][j]);
456 }
789 }
The elements of the transposed matrix are for(i=0;i<rows_sum;i++)
147 {
258 for(j=0;j<cols_sum;j++)
369 sum[i][j] = mat1[i][j] + mat2[i][j];
}
printf("\n The elements of the resultant matrix are ");
for(i=0;i<rows_sum;i++)
{

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 24
printf("\n"); {
for(j=0;j<cols_sum;j++) scanf("%d",&mat1[i][j]);
printf("\t %d", sum[i][j]); }
} }
return 0; printf("\n Enter the elements of the second matrix ");
} for(i=0;i<rows2;i++)
{
Output for(j=0;j<cols2;j++)
Enter the number of rows in the first matrix: 2 {
Enter the number of columns in the first matrix: 2 scanf("%d",&mat2[i][j]);
Enter the number of rows in the second matrix: 2 }
Enter the number of columns in the second matrix: 2 }
Enter the elements of the first matrix for(i=0;i<res_rows;i++)
1234 {
Enter the elements of the second matrix for(j=0;j<res_cols;j++)
5678 Arrays 103
The elements of the resultant matrix are {
68 res[i][j]=0;
10 12 for(k=0; k<res_cols;k++)
res[i][j] += mat1[i][k] * mat2[k][j];
3.Write a program to multiply two m x n }
matrices. }
#include <stdio.h> printf("\n The elements of the product matrix are ");
int main() for(i=0;i<res_rows;i++)
{ {
int i, j, k; printf("\n");
int rows1, cols1, rows2, cols2, res_rows, res_cols; for(j=0;j<res_cols;j++)
int mat1[5][5], mat2[5][5], res[5][5]; printf("\t %d",res[i][j]);
clrscr(); }
printf("\n Enter the number of rows in the first return 0;
matrix : "); }
scanf("%d",&rows1); Output
printf("\n Enter the number of columns in the first Enter the number of rows in the first matrix: 2
matrix : "); Enter the number of columns in the first matrix: 2
scanf("%d",&cols1); Enter the number of rows in the second matrix: 2
printf("\n Enter the number of rows in the second Enter the number of columns in the second matrix: 2
matrix : "); Enter the elements of the first matrix
scanf("%d",&rows2); 1234
printf("\n Enter the number of columns in the second Enter the elements of the second matrix
matrix : "); 5678
scanf("%d",&cols2); The elements of the product matrix are
if(cols1 != rows2) 19 22
{ 43 50
printf("\n The number of columns in the first matrix
must be equal
to the number of rows in the second matrix");
exit();
}
res_rows = rows1;
res_cols = cols2;
printf("\n Enter the elements of the first matrix ");
for(i=0;i<rows1;i++)
{
for(j=0;j<cols1;j++)

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 25
Pointer and 2D Array: Pointer and 3D Array
Write a program to read and display a 3 x 3 Write a program which illustrates the use of a
matrix. pointer to a three-dimensional array.
#include <stdio.h> #include <stdio.h>
#include <conio.h> int main()
void display(int (*)[3]); {
int main() int i,j,k;
{ int arr[2][2][2];
int i, j, mat[3][3]; int (*parr)[2][2]= arr;
clrscr(); clrscr();
printf("\n Enter the elements of the matrix"); printf("\n Enter the elements of a 2 \ 2 \ 2 array: ");
for(i=0;i<3;i++) for(i = 0; i < 2; i++)
{ {
for(j = 0; j < 3; j++) for(j = 0; j < 2; j++)
{ {
scanf("%d", &mat[i][j]); for(k = 0; k < 2; k++)
} scanf("%d", &arr[i][j][k]);
} }
display(mat); }
return 0; printf("\n The elements of the 2 \ 2 \ 2 array are: ");
} for(i = 0; i < 2; i++)
void display(int (*mat)[3]) {
{ for(j = 0; j < 2; j++)
int i, j; {
printf("\n The elements of the matrix are"); for(k = 0; k < 2; k++)
for(i = 0; i < 3; i++) printf("%d", *(*(*(parr+i)+j)+k));
{ }
printf("\n"); }
for(j=0;j<3;j++) return 0;
printf("\t %d",*(*(mat + i)+j)); }
} Output
} Enter the elements of a 2 \ 2 \ 2 array: 1 2 3 4 5 6 7 8
Output The elements of the 2 \ 2 \ 2 array are: 1 2 3 4 5 6 7 8
Enter the elements of the matrix
123456789 Note In the printf statement, you could also have used
The elements of the matrix are * ( * ( * ( a r r + i ) + j + ) + k ) instead of
123 *(*(*(parr+i)+j)+k)).
456
789

Advantages of using Arrays:


• Arrays allow random access to elements. This makes accessing elements by position faster.
• Arrays have better cache locality which makes a pretty big difference in performance.
• Arrays represent multiple data items of the same type using a single name.
• Arrays store multiple data of similar types with the same name.
• Array data structures are used to implement the other data structures like linked lists, stacks, queues, trees,
graphs, etc.

Disadvantages of Array:
• As arrays have a fixed size, once the memory is allocated to them, it cannot be increased or decreased,
making it impossible to store extra data if required. An array of fixed size is referred to as a static array.
• Allocating less memory than required to an array leads to loss of data.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 26
• An array is homogeneous in nature so, a single array cannot store values of different data types.
• Arrays store data in contiguous memory locations, which makes deletion and insertion very difficult to
implement. This problem is overcome by implementing linked lists, which allow elements to be accessed
sequentially.

Application of arrays
• They are used in the implementation of other data structures such as array lists, heaps, hash tables, vectors,
and matrices.
• Database records are usually implemented as arrays.
• It is used for different sorting algorithms such as bubble sort insertion sort, merge sort, and quick sort.
• It is used for implementing matrices.
• Graphs are also implemented as arrays in the form of an adjacency matrix.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 27
[T-6] Sparse Matrices and their representations

• A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n
values.
• If most of the elements of the matrix have 0 value, then it is called a sparse matrix.

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..
Example:
00304
00570
00000
02600

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:
1. Array representation
2. Linked list representation*

Method 1: Using Arrays:


2D array is used to represent a sparse matrix in which there are three rows named as
• Row: Index of row, where non-zero element is located
• Column: Index of column, where non-zero element is located
• Value: Value of the non zero element located at index – (row,column)

Implementation in C

// C program for Sparse Matrix Representation // using Array


#include<stdio.h>
int main()
{ // Assume 4x5 sparse matrix
int sparseMatrix[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 28
int size = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
size++;

// number of columns in compactMatrix (size) must be equal to number of non - zero elements in sparseMatrix

int compactMatrix[3][size];

// Making of new matrix


int k = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
{
compactMatrix[0][k] = i;
compactMatrix[1][k] = j;
compactMatrix[2][k] = sparseMatrix[i][j];
k++;
}

for (int i=0; i<3; i++)


{
for (int j=0; j<size; j++)
printf("%d ", compactMatrix[i][j]);

printf("\n");
}
return 0;
}

Output
001133
242312
345726

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 29
Programs/Questions

1. What are arrays and why are they needed?


2. How is an array represented in the memory?
3. How is a two-dimensional array represented in the memory?
4. What is the use of multi-dimensional arrays?
5. Explain sparse matrix.
6. How are pointers used to access two-dimensional arrays?
7. Why does storing of sparse matrices need extra consideration? How are sparse matrices stored efficiently in the
computer’s memory?
8 Consider a two-dimensional array Marks [10][5] having its base address as 2000 and the number of bytes per
element of the array is 2. Now, compute the address of the element, Marks [8][5], assuming that the elements are
stored in row major order.
9. Write a program that reads an array of 100 integers. Display all the pairs of elements whose sum is 50.
10. Write a program to interchange the second element with the second last element.
11. Write a program that calculates the sum of squares of the elements.
12. Write a program to compute the sum and mean of the elements of a two-dimensional array.
13. Write a program to read and display a square (using functions).
14. Write a program that computes the sum of the elements that are stored on the main diagonal of a matrix using
pointers.
15. Write a menu driven program to read and display a 2D matrix. Also, find the sum, transpose, and product of
the two matrices.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 30
Lecture Notes || Unit -2
CO-2 Understand and implement linked lists and associated operations.
Syllabus: Linked lists: Array Implementation and Pointer Implementation of Singly Linked Lists, Doubly Linked List,
Circularly Linked List, Operations on a Linked List. Insertion, Deletion, Traversal, Polynomial Representation and
Addition Subtraction Multiplications of Single variable Polynomials

[T-7] Linked lists: Singly Linked List

Why use linked list over array? • Singly linked list can be defined as the
• Till now, we were using array data collection of ordered set of elements. The
structure to organize the group of elements number of elements may vary according to
that are to be stored individually in the need of the program.
memory. However, Array has several • A node in the singly linked list consist of
advantages and disadvantages which must two parts: data part and link part.
be known in order to decide the data • Data part of the node stores actual
structure which will be used throughout the information that is to be represented by the
program. node while the link part of the node stores
• Array contains following limitations: the address of its immediate successor.
a) The size of array must be known in • we can not traverse the list in the reverse
advance before using it in the program. direction.
Increasing size of the array is a time Example:
taking process.
b) It is almost impossible to expand the size
of the array at run time.
c) All the elements in the array need to be
contiguously stored in the memory.
d) Inserting any element in the array needs
shifting of all its predecessors.
• Linked list is the data structure which can Here, every node points to the next node, the last node is
overcome all the limitations of an array. a pointer to NULL for the end of the list and the head is
Using linked list is useful because, pointing to the first node.
a) It allocates the memory dynamically.
b) All the nodes of linked list are non- Singly Linked List and its Operations:
contiguously stored in the memory and 1. Traversing the Singly Linked List
linked together with the help of pointers. 2. Insertion of a Node at the Beginning of the List
c) Sizing is no longer a problem since we 3. Insertion of a Node at the End of the List
do not need to define its size at the time 4. Insertion of a New Node at the Given Position
of declaration. 5. Deletion of a Node from the Beginning of the List
d) List grows as per the program's demand 6. Deletion of a Node from the End of the List
and limited to the available memory 7. Deletion of a Node from the Given Position
space. 8. Search a Node Data in the List
9. Update a Node Data
What is a Linked List?
• A linked list is a kind of linear data structure in Node Syntax:
which the data is stored in a non-contiguous struct node
memory location. { int data;
• List size is limited to the memory size and doesn't struct node* link;
need to be declared in advance. };
• Empty node can not be present in the linked list. struct node* head = NULL;
• We can store values of primitive types or objects
in the singly linked list. 1. Traversing the Singly Linked List
1. Take any temporary node type of pointer
What is a Singly Linked List? temp and point it to the head pointer.
2. Start iterating using temp until it does not

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 31
reach the NULL value.
3. Print the data of that node which is pointing by 3. Insertion of a Node at the End of the List
the temp node.
Algorithm:
void print(void) 1. START
{ struct node* temp = head; 2. Create a new node and assign the data
while(p != NULL) 3. Find the last node
{ printf("->%d ", temp->data); 4. Point the last node to new node
temp = temp->next; 5. END
}
printf(“\n”); //Insert the new node at the end of the list
} void insertatlast(int data)
{ struct node* new_node;
2. Insertion of a Node at the Beginning of the List new_node=(struct node*)malloc(sizeof(struct node));
new_node->data = data;
Algorithm: new_node->next=NULL;
1. START struct node* temp = head;
2. Create a node to store the data
3. Check if the list is empty //getting the last node
4. If the list is empty, add the data to the node and while(temp->next != NULL)
Assign the head pointer to it. { temp = temp->next;
5. If the list is not empty, add the data to a node and }
link to the current head. Assign the head to the //link the last node next pointer to the new node
newly added node. temp->next = new_node;
6. END }

// Insert the new node at the beginning of the list Example: Inserting a new node with data 88 at the end of
void insertatbegin(int data) the list.
{ struct node* new_node; Step 1: Traversing the list, and reach at the last node
new_node =(struct node*)malloc(sizeof(struct node)); while(temp->next != NULL)
new_node->data = data; { temp = temp->next; }
new_node->next=head;
head = new_node;
}

Example: Let’s insert a new node with data 10 at the


beginning of the given list.
Step 1: Updating the next of the new node to head
node(new_node->next=head;)
Step 2: Update the next of the temp to the new node
(temp->next = new_node;)

Step 2: Updating the head pointer to the new


node(head = new_node;)

4. Insertion of a New Node at the Given


Position

Algorithm:
1. START
2. Create a new node and assign data to it

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 32
3. Iterate until the node at position is found
4. Point first to new first node 5. Deletion of a Node from the Beginning of the List
5. END.
Agorithm:
//Insert the new node at the given position 1. START
void insrtatposition(int data, int pos) 2. Assign the head pointer to the next node in
{ int i; the list
struct node* new_node; 3. END
new_node =(struct node*)malloc(sizeof(struct
node)); //Delete the node from the beginning of the list
new_node->data=data; void delatbegin()
new_node->next=NULL; {struct node* temp = head;
struct node* temp = head; if(temp == NULL)
for(i=2;i<pos;i++) {
{temp=temp->next; printf("no node to delete");
} }
new_node->next = temp->next; else
temp->next = new_node; {temp=temp->next;
head =temp;
}
Example: Inserting a new node with data 34 at position }
3 in the given list. }
Step 1: Traverse the list and reach at the given
Position Example: Deleting the node from the beginning in the
for(i=2;i<pos;i++) given list.
{temp=temp->next; Step 1: Store the head node to the temp and move head to
} its next node
temp=temp->next;
head =temp;

Step 2: new_node->next = temp->next;


temp->next = new_node;

6. Deletion of a Node from the End of the Node

Algorithm:
1. START
2. Iterate until you find the second last element
in the list.
3. Assign NULL to the second last element in
the list.
4. END

//Delete the node from the ending of the list


void delatlast()
{ struct node* temp = head;
//reaching the last node
while(temp->next->next != NULL)
{

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 33
temp = temp->next;
}
temp->next=NULL;
}

Example: Deleting the last node of the given list.


Step 1: Traverse the list at the one node before the last
Node
while(temp->next->next != NULL)
{ temp = temp->next;
} Step 2: temp->next=temp->next->next;

Step 2: Update the next of temp node to NULL


temp->next=NULL; 8. Search a Node Data in the List
To find a node with the given key, we need to traverse the
list from start to end and match the data with the key
void search(int data)
{ int position = 0;
int flag = 0;
struct node* temp = head;
while(temp != NULL)
{ position += 1;
7. Deletion of a Node from the Given Position if(temp->data == data)
{
Algorithm: flag = 1;
1. START break;
2. Iterate until find the current node at position }
in the list. temp = temp->next;
3. Assign the adjacent node of current node in }
the list to its previous node. if(flag == 0)
4. END { printf("\nNode with data %d was not found!\n",
data);
//Deleting the node from the given position }
void delatposition(int pos) else
{int i; { printf("\nFound data at %d position\n",
struct node* temp = head; position);
struct node* prev = NULL; }
for(i=2;i<pos;i++) }
{temp=temp->next;
} 9. Update a Node Data
temp->next=temp->next->next; Updation is the process to change the value of a node. To
} update the node data we have to follow the given steps:
1. Traverse the list from start to the given position.
Example: Deleting the node at position 3 in the given list. 2. Update the value of that node.
Step 1: Traverse the list at the given position
for(i=2;i<pos;i++) *Write a C program to search any value given by the user
{temp=temp->next; and replace it by 99.
}

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 34
Program to demonstrate operations on singly // Insert the new node at the beginning of the list
Linked List void insertatbegin(int data)
#include<stdio.h> {
#include<stdlib.h> struct node* new_node;
//type declaration of a node new_node =(struct node*)malloc(sizeof(struct
struct node node));
{ int data; new_node->data = data;
struct node *next; new_node->next=head;
}; head = new_node;
struct node* head = NULL; }
//prototyping of the functions
void insertatbegin(int); //Insert the new node at the end of the list
void insertatlast(int); void insertatlast(int data)
void insertatposition(int, int); {
void delatbegin(); struct node* new_node;
void delatlast(); new_node =(struct node*)malloc(sizeof(struct
void delatposition(int); node));
void print(); new_node->data = data;
void search(int); new_node->next=NULL;
void update (int, int); struct node* last = head;
int main()
{ //getting the last node
while(last->next != NULL)
insertatbegin(22); {
insertatbegin(33); last = last->next;
insertatbegin(44); }
insertatbegin(55); //link the last node next pointer to the new node
insertatbegin(66); last->next = new_node;
printf("after insertion at beginning\n"); }
print();
insertatlast(77); //Insert the new node at the given position
printf("after inserting 77 at last\n"); void insertatposition(int data, int pos)
print(); { int i;
insertatposition(99,4); struct node* new_node;
printf("After Inserting a node (99) at the position at new_node =(struct node*)malloc(sizeof(struct
4\n"); node));
print(); new_node->data=data;
delatbegin(); new_node->next=NULL;
printf("afterDeleting a node from beginning\n"); struct node* temp = head;
print();
delatlast(); for(i=2;i<pos;i++)
printf("after Deleting a node from end\n"); {temp=temp->next;
print(); }
delatposition(4); new_node->next = temp->next;
printf("after Deleting a node from 4th position\n"); temp->next = new_node;
print();
printf("\nSearching the node 33"); }
search(33);
return 0; //Delete the node from the beginning of the list
} void delatbegin()
{struct node* temp = head;
if(temp == NULL)
{
printf("no node to delete");

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 35
} }
else if(flag == 0)
{temp=temp->next; { printf("\nNode with data %d was not found!\n",
head =temp; data);
} }
} else
{ printf("\nFound data at %d position\n",
//Delete the node from the ending of the list position);
void delatlast() }
{ struct node* temp = head; }
while(temp->next->next != NULL)
{
temp = temp->next; // Prints the data from the start of the list
} void print(void)
temp->next=NULL; {
} struct node* temp = head;

//Deleting the node from the given position while(temp != NULL)


void delatposition(int pos) {
{int i; printf("->%d ", temp->data);
struct node* temp = head; temp = temp->next;
struct node* prev = NULL; }
for(i=2;i<pos;i++) Printf(“\n”);
{temp=temp->next; }
}
temp->next=temp->next->next;

//Search the node with given data in the list


void search(int data)
{
int position = 0;
int flag = 0;
struct node* temp = head;
while(temp != NULL)
{ position += 1;
if(temp->data == data)
{ flag = 1;
break;
}
temp = temp->next;

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 36
[T-8] Doubly Linked List
Traversing the Doubly Linked List from end
What is a Doubly Linked List in C? void print_from_end()
• A doubly linked list is a kind of linked list in which { struct node* temp = head;
each node has three fields, one is data, and the while (temp->next != NULL)
addresses of the next and previous nodes. {
• In a doubly linked list, traversing can happen in both
temp = temp->next;
forward and backward directions.
Example: }

// Traverse backward and print the data


while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->prev;
}
}

2. Insertion of a Node at the Beginning of the


Node Representation- List
struct node Algorithm:
{ 1. START
struct node* prev; 2. Create a new node with three variables: prev, data,
int data; next.
struct node* next; 3. Store the new data in the data variable
}; 4. If the list is empty, make the new node as head.
5. Otherwise, link the address of the existing first node
struct node* head = NULL; to the next variable of the new node, and assign null to
the prev variable.
Operations on Doubly Linked List: 6. Point the head to the new node.
7. END
1. Traversing the Doubly Linked List
To traverse the doubly linked list, we have void insertatbegin(int data)
to follow the below steps:
1. Take a temporary pointer temp and {
initialise with the head pointer. struct node* new_node;
2. Start iterating from start to end. new_node = (struct node*) malloc(sizeof(struct
3. On every iteration print the data of the node));
node. new_node->prev = NULL;
new_node->data = data;
Traversing the Doubly Linked List from beginning new_node->next = NULL;
void print()
{ struct node* temp = head; if(head == NULL)
while (temp != NULL) {head = new_node;
{ }
printf("->%d ", temp->data); else
temp = temp->next; {
} head->prev = new_node;
printf("\n"); new_node->next = head;
}
head = new_node;
}

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 37
} 3. If the list is not empty, find the last node of the list.
4. Create a link between the last node in the list and the
Example: Insert the new node with data 34 at the new node.
beginning in the given doubly linked list. 5. The new node will point to NULL as it is the new last
Given Doubly Linked and a new node with data node.
34: 6. END

void insertatlast(int data)


void insertatlast(int data)
{
struct node* new_node;
new_node = (struct node*) malloc(sizeof(struct
node));
new_node->prev = NULL;
Step 1: Update the next pointer of the new node to
the head node.( new_node->next = head;) new_node->data = data;
new_node->next = NULL;

if (head == NULL)
{
head = new_node;
}
else
{ struct node* temp = head;
Step 2: Change the previous pointer of the head //traverse to the last node
node to the new node. while (temp->next != NULL)
( head->prev = new_node;) {
temp =temp->next;
}
temp->next = new_node;
new_node->prev = temp;
}
}
Example: Insert a new node with data 99 at
Step 3: Update the head pointer to the new node. the end of the given doubly linked list.
(head = new_node;) Given the doubly linked list and a new node
with data 99.

Step 1: Traverse the list to the last node.


3. Insertion of a Node at the End of the List while (temp->next != NULL)
{
Algorithm:
temp =temp->next;
1. START
2. If the list is empty, add the node to the list and point }
the head to it.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 38
void insertatposition(int data, int pos)
{ int i;
struct node* new_node;
new_node = (struct node*) malloc(sizeof(struct
node));
new_node->prev = NULL;
new_node->data = data;
new_node->next = NULL;
Step 2: Update the next pointer of the last node to
the new node. struct node* temp = head;
temp->next = new_node; //traverse to the before given position
for (int i=2;i<pos;i++)
{
temp = temp->next;
}
temp->next->prev = new_node;
new_node->next = temp->next;
temp->next = new_node;
new_node->prev = temp;
}
Step 3: Update the previous pointer of the new Example: Add a new node at position 3 with the
node to the last node. data 44.
new_node->prev = temp;

Step 1: Traverse the list from the start to the K-1th


4. Insertion of a New Node at the Given node. (here, K = 3)
Position for (int i=2;i<pos;i++)
To insert a new node at some position we
{
need to do the following steps:
1. Traverse the list from start to the position temp = temp->next;
K-1, where K is the given position. }
2. Update the previous pointer of the Kth
node to the new node.
3. Update the next pointer of the new node
to the Kth node.
4. Update the next pointer of the K-1th node
to the new node.
5. Update the previous pointer of the new
node to the K-1th node.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 39
Step 2: Update the previous pointer of the Kth
node to the new node. 5. Delete a Node from the Beginning of the List
temp->next->prev = new_node;
Algorithm:
1. START
2. Check the status of the doubly linked list
3. If the list is empty, deletion is not possible
4. If the list is not empty, the head pointer is
shifted to the next node.
5. END

void delfrombegin()
{if (head == NULL)
Step 3: Update the next pointer of the new node {
new_node->next = temp->next; printf("no node to delete");
}
head = head->next;
}
Example: Delete the node with value 78 from the
beginning in the given doubly linked list.

Step 4: Update the next pointer of the K-1th node


to the new node. temp->next = new_node;

Step 1: head = head->next;

Step 5: Update the previous pointer of the new


node to the K-1th node.
new_node->prev = temp;
6. Delete a Node from the End of the List
To delete the node from the end of the list
takes the following steps to complete this
operation.
1. Traverse to the second last node of the
list, let’s say K.
2. Store the K+1th node (last node) into
some temporary variable.
3. Update the next pointer of the Kth node to
NULL.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 40
void delfromlast()
{ if (head == NULL)
{ 7. Delete a Node from the Given Position
printf("no node to delete"); Deleting a node from the given position
needs the following steps:
} 1. Traverse the list to the given position K.
struct node* temp = head; 2. Update the next pointer of the K-1th node
while (temp->next != NULL) to the K+1th node.
{ 3. Update the previous pointer of the K+1th
temp = temp->next; node to the K-1th node.
}
temp->prev->next = temp->next; void delfromposition(int pos)
} { if (head == NULL)
{
Example: delete the node having data 23 printf("no node to delete");
from the end of the doubly linked list. }

struct node* temp = head;


for (int i=2;i<=pos;i++)
{
temp = temp->next;
}
//update links
temp->prev->next = temp->next;
Step 1: Traverse to the second last node of the list,
temp->next->prev=temp->prev;
let’s say K.
}
while (temp->next != NULL)
{ Example: Delete the 2nd node having data 34 in
temp = temp->next; the given doubly linked list.
}

Step 1: Traverse the list to the given position K.


Step 2: temp->prev->next = temp->next; for (int i=2;i<=pos;i++)
{
temp = temp->next;
}

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 41
Step 2: temp->prev->next = temp->next; {
temp->next->prev=temp->prev; if (temp->data == data)
{
flag = 1;
break;
}
temp = temp->next;
}

if (flag == 0)
{
printf("\n not found\n");
}
else
{
printf("\nfound\n");
}
}

9. Update a Node Data in the Doubly Linked


List
Updation is a process to change the current
8. Search a Node Data in the List value of the node. To update the value of a
Searching in a linked list is a technique to node needs to follow these steps:
find out the node that has the desired data. 1. Reach to that node to which we want to
Searching takes the following steps to get update using list traversal.
that node: 2. Update the node value by the new value.
1. Traverse from the start of the node to the
end of the node.
2. On each iteration check whether the node
data is the same as we want.

void search(int data)


{ struct node* temp = head;
int position = 0;
int flag = 0;
while (temp != NULL)

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 42
//DLL Implementation new_node = (struct node*) malloc(sizeof(struct
node));
#include<stdio.h> new_node->prev = NULL;
#include<stdlib.h> new_node->data = data;
struct node new_node->next = NULL;
{ struct node* prev; if(head == NULL)
int data; {head = new_node;
struct node* next; }
}; else
struct node* head = NULL; { head->prev = new_node;
/* functions prototyping */ new_node->next = head;
void insertatbegin(int); head = new_node;
void insertatlast(int); }
void insertatposition(int, int); }
void delfrombegin();
void delfromposition(int); void print()
void delfromlast(); { struct node* temp = head;
void print(); while (temp != NULL)
void search(int); {
void print_from_end(); printf("->%d ", temp->data);
int main() temp = temp->next;
{ insertatbegin(22); }
insertatbegin(33); printf("\n");
insertatbegin(44); }
insertatbegin(55);
insertatbegin(66); void insertatlast(int data)
printf("\nAfter Inserting all nodes at beginning {
manner\n"); struct node* new_node;
print(); new_node = (struct node*) malloc(sizeof(struct
printf("\nTraversal/ printing from end\n"); node));
print_from_end(); new_node->prev = NULL;
insertatlast(77); new_node->data = data;
printf("\nAfter Inserting 77 at last\n "); new_node->next = NULL;
print(); if (head == NULL)
insertatposition(99,4); { head = new_node;
printf("\nAfter Inserting 99 at position 4\n"); }
print(); else
delfrombegin(); { struct node* temp = head;
printf("\nAfter deleting first node\n"); //traverse to the last node
print(); while (temp->next != NULL)
delfromlast(); { temp =temp->next;
printf("\nAfter deleting last node\n"); }
print(); temp->next = new_node;
delfromposition(3); new_node->prev = temp;
printf("\nAfter deleting node from position 3\n"); }
print(); }
printf("\nSearching data 44\n");
search(44); void insertatposition(int data, int pos)
{ int i;
return 0; struct node* new_node;
} new_node = (struct node*) malloc(sizeof(struct
void insertatbegin(int data) node));
{ struct node* new_node; new_node->prev = NULL;
new_node->data = data;

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 43
new_node->next = NULL; if (temp->data == data)
struct node* temp = head; {
//traverse to the before given position flag = 1;
for (int i=2;i<pos;i++) break;
{ temp = temp->next; }
} temp = temp->next;
}
temp->next->prev = new_node;
new_node->next = temp->next; if (flag == 0)
temp->next = new_node; {
new_node->prev = temp; printf("\n not found\n");
} }
else
void delfrombegin() {
{if (head == NULL) printf("\nfound\n");
{ printf("no node to delete"); }
} }
struct node* temp = head;
head = head->next;
} void print_from_end()
{ struct node* temp = head;
void delfromlast() while (temp->next != NULL)
{ if (head == NULL) {
{ temp = temp->next;
printf("no node to delete"); }
}
struct node* temp = head; // Traverse backward and print the data
while (temp->next != NULL) while (temp != NULL)
{ temp = temp->next; {
} printf("%d ", temp->data);
temp->prev->next = temp->next; temp = temp->prev;
} }
}
void delfromposition(int pos)
{ if (head == NULL)
{
printf("no node to delete");
}

struct node* temp = head;


for (int i=2;i<=pos;i++)
{
temp = temp->next;
}
//update previous node
temp->prev->next = temp->next;
}

void search(int data)


{ struct node* temp = head;
int position = 0;
int flag = 0;
while (temp != NULL)
{

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 44
{
[T-9] Circular Singly Linked List in C printf("->%d ", temp->data);
temp = temp->next;
What is a Circular Singly Linked List? } while (temp != head);
• Circular Linked List is a kind of singly linked list printf("\n");
in which the last node of a list is pointing to the }
first node.
3. Insert a Node at Beginning of the List
void insertatbegin(int data)
{ struct node *newNode = (struct node
*)malloc(sizeof(struct node));
if (newNode == NULL)
{
printf("Memory allocation failed.\n");
}
Circular Singly Linked List and its Operations in
C:
1. Type Declaration of a Linked List // Assign data to the new node
2. Traversing the Circular Singly Linked List newNode->data = data;
3. Insertion of a Node at the Beginning of the List
4. Insertion of a Node at the End of the List // If the list is empty, set the new node as the
head and make it circular
5. Insertion of a New Node at the Given Position
if (head == NULL)
6. Deletion of a Node from the Beginning of the List
{
7. Deletion of a Node from the End of the List
head = newNode;
8. Deletion of a Node from the Given Position
newNode->next = head;
9. Search a Node Data in the List
}
10. Update a Node Data
else
{
1. Type Declaration of a Linked List
We have defined the type declaration of a node in // Traverse to the last node
the circular singly linked list. struct node *last = head;
while (last->next != head)
{
last = last->next;
Node Syntax: }
struct node
{ // Update pointers to insert the new node at
int data; the beginning
struct node* next; newNode->next = head;
}; last->next = newNode;
head = newNode;
2. Traversing the Circular Singly Linked List }
void print() }
{ struct node *temp = head;
if (head == NULL) Step 1: Traverse the list to the last node.
{ // Traverse to the last node
printf("\n List is Empty! \n"); struct node *last = head;
} while (last->next != head)
{
printf("\n"); last = last->next;
do

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 45
} 2. Update the next pointer of the last
node to the new node.
3. Update the next pointer of the new
node to the head node.

void insertatlast(int data)


{
struct node *new_node ;
Step 2: Update the next pointer of the last node to the new_node = (struct node
new node. *)malloc(sizeof(struct node));
last->next = newNode; new_node->data = data;
new_node->next = NULL;

if (new_node != NULL)
{ // if the list is empty
if (head == NULL)
{
head = new_node;
new_node->next = head;
Step 3: Update the next pointer of the new node to
the head node. }
newNode->next = head;
struct node *last = head;

// traverse to the end node


while (last->next != head)
{
last = last->next;
}

Step 4: Update the head node to the new node. // update the last node to the new node
head = newNode;
last->next = new_node;

// update the next pointer of the new node to


the head node
new_node->next = head;
}
}

Example: Insert a new node with data 35 at the


end of the list.

Step 1: Traverse the list to the last node.


// traverse to the end node
4. Insert a Node at the End
The size of the list increased by one on the while (last->next != head)
insertion of a new node. We have to follow {
the given steps to insert a new node at the end last = last->next;
of the list. }
1. Traverse the list to the last node.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 46
struct node *temp = head;
// Since, temp is already pointing to first node
// then count will be start at second node
// traverse the list to the given position
for(int i=2;i<position;i++)
{
temp = temp->next;
}
Step 2: Update the next pointer of the last node to the
new node. // update the new node to the temp (position
node)
last->next = new_node;
new_node->next = temp->next;

// update the prev node to the new node


temp->next = new_node;
}
Example: Insert a new node with data 35 at position
2.
Step 1: Traverse the list to the given position K = 3.
(1-based index)
for(int i=2;i<=position;i++)
Step 3: Update the next pointer of the new node to
the head node. {
new_node->next = head; temp = temp->next;
}

5. Insert a Node at a Given Position


Inserting a new node at the given position needs to
follow the given steps: Step 2: Update the next pointer of the K-1th node to
1. Traverse the list to the given position K. the new node.
2. Update the next pointer of the K-1th node to the temp->next = new_node;
new node.
3. Update the next pointer of the new node to the
Kth node.

void insertatposition(int position, int data)


{
struct node *new_node ;
new_node = (struct node *)malloc(sizeof(struct
node));
new_node->data = data;
new_node->next = NULL;

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 47
Step 3: Update the next pointer of the new node to Example: Deleting a node with data 56 from the
the Kth node. beginning of the list.
new_node->next = temp->next; Step 1: Traverse the list to the end node.
while (last->next != head)
{
last = last->next;
}

6. Delete a Node from the Beginning


Deletion of a node reduces the size of the list by one.
Deletion requires the following steps:
1. Traverse the list to the end node. Step 2: Update the next pointer of the last node to the
2. Update the next pointer of the last node to next of the head node.
the next of the head node. last->next = head;
3. Update the head to the next of the head node.

void delatbegin()
{ // check where the list is empty or not
if (head == NULL)
{
printf("\n List is Empty! \n");
}
Step 3: Update the head to the next of the head node.
// traverse to the end of the list head = head->next;
struct node *last = head;

// if only one node in the list


if (last->next == head)
{
head = NULL;
}

// traverse to the last node


7. Delete a Node from the End
while (last->next != head) Deletion of a node from the end of the circular singly
{ linked list takes the following steps:
last = last->next; 1. Traverse the list to the N-1th node, where N
} is the number of nodes.
2. Update the next pointer of the N-1th node to
head = head->next; the head node.
last->next = head; void delatlast()
{
} // check where the list is empty or not
if (head == NULL)

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 48
{ 1. Traverse the list upto the given position K.
printf("\n List is Empty! \n"); 2. Update the next pointer of the K-1th node to
} the K+1th node.
void delatposition(int position)
struct node *temp=head; void delatposition(int position)
{int i;
// if only one node in the list struct node* temp = head;
if (temp->next == head) for(i=2;i<position;i++)
{ {temp=temp->next;
head = NULL; }
} temp->next=temp->next->next;
while (temp->next->next != head) }
{
Example: Deleting the 3rd node of the given list.
temp = temp->next; Step 1: Traverse the list upto the given position.
} for(i=2;i<position;i++)
temp->next = head; {temp=temp->next;
} }
Example: Deleting the last node having data 35.
Step 1: Traverse the list to the N-1th node, where N
is the number of nodes.
while (temp->next->next != head)
{
temp = temp->next;
}
Step 2: Update the next pointer of the K-1th node to
the K+1th node.
temp->next=temp->next->next;

Step 2: Update the next pointer of the N-1th node to


the head node.
temp->next = head;
9. Search a Node Data in the List
Searching is the process to find a value in the linked
list. We have to follow the given steps to search the
value in the list.
1. Traverse from start to end of the list.
2. Match the node data with the given key.
// search a data into the list
void search(int key)
{
8. Delete a Node from the Given Position struct node* temp = head;
To delete a node from the given position, we have to
follow the given steps: do

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 49
{ insertatlast(88);
if (temp->data == key) printf("\nList After inserting 88 at the end
{ of list\n");
printf("\n\t Data Found\n"); print();
return; insertatposition(4,99);
} printf("\nList After inserting 99 at the 4th
temp = temp->next; postion\n");
}while (temp->next != head); print();
printf("\n\tData not Found\n"); delatbegin();
} printf("\nList After deleting beginning
node\n");
10. Update the Node Data print();
Updation is the process to change the current node delatlast();
value with the new value. It needs to follow the printf("\nList After deleting last node\n");
given steps: print();
1. Traverse the list upto the given position.
2. Update the value of the node with the new delatposition(4);
given value. printf("\nList After deleting node at position
4\n");
print();
//CSLL Implementation printf("\nSearching the data 44\n");
#include <stdio.h> search(44);
#include <stdlib.h> return 0;
struct node }
{ int data;
struct node *next; void insertatbegin(int data)
}; { struct node *newNode = (struct node
struct node *head=NULL; *)malloc(sizeof(struct node));
// function prototyping if (newNode == NULL)
void insertatbegin(int); {
void insertatlast(int); printf("Memory allocation failed.\n");
void insertatposition(int, int); }
void delatbegin();
void delatlast(); // Assign data to the new node
void delatposition(int); newNode->data = data;
void search(int);
void print(); // If the list is empty, set the new node as
int main() the head and make it circular
{ if (head == NULL)
insertatbegin(11); {
insertatbegin(22); head = newNode;
insertatbegin(33); newNode->next = head;
insertatbegin(44); }
insertatbegin(55); else
insertatbegin(66); {
insertatbegin(77); // Traverse to the last node
printf("\nList After inserting elements struct node *last = head;
[inserting at begin manner]\n"); while (last->next != head)
print(); {

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 50
last = last->next; new_node->next = NULL;
}
struct node *temp = head;
// Update pointers to insert the new // Since, temp is already pointing to first
node at the beginning node
newNode->next = head; // then count will be start at second node
last->next = newNode; // traverse the list to the given position
head = newNode; for(int i=2;i<position;i++)
} {
} temp = temp->next;
}
void insertatlast(int data)
{ // update the new node to the temp
struct node *new_node ; (position node)
new_node = (struct node new_node->next = temp->next;
*)malloc(sizeof(struct node));
new_node->data = data; // update the prev node to the new node
new_node->next = NULL; temp->next = new_node;
}
if (new_node != NULL)
{ // if the list is empty void delatbegin()
if (head == NULL) {
{ // check where the list is empty or not
head = new_node; if (head == NULL)
new_node->next = head; {
} printf("\n List is Empty! \n");
struct node *last = head; }

// traverse to the end node // traverse to the end of the list


while (last->next != head) struct node *last = head;
{
last = last->next; // if only one node in the list
} if (last->next == head)
{
// update the last node to the new node head = NULL;
last->next = new_node; }

// update the next pointer of the new // traverse to the last node
node to the head node while (last->next != head)
new_node->next = head; {
} last = last->next;
} }

void insertatposition(int position, int data) head = head->next;


{ struct node *new_node ; last->next = head;
new_node = (struct node
*)malloc(sizeof(struct node)); }
new_node->data = data;

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 51
void delatlast() } while (temp != head);
{
// check where the list is empty or not printf("\n");
if (head == NULL) }
{
printf("\n List is Empty! \n");
} void search(int key)
{
struct node *temp=head; struct node* temp = head;

// if only one node in the list do


if (temp->next == head) {
{ if (temp->data == key)
head = NULL; {
} printf("\n\t Data Found\n");
return;
while (temp->next->next != head) }
{ temp = temp->next;
temp = temp->next; }while (temp->next != head);
} printf("\n\tData not Found\n");
}
temp->next = head;

void delatposition(int position)


{int i;
struct node* temp = head;
for(i=2;i<position;i++)
{temp=temp->next;
}
temp->next=temp->next->next;

void print()
{
struct node *temp = head;
if (head == NULL)
{
printf("\n List is Empty! \n");
}
printf("\n");
do
{
printf("->%d ", temp->data);
temp = temp->next;

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 52
[T-10] Polynomial Representation and Addition Multiplication of Polynomials:
Subtraction Multiplications of Single variable To multiply two polynomials, you can use the
Polynomials distributive property and then combine like terms.

A single variable polynomial is an algebraic


expression consisting of a sum of terms, where each
term is a constant multiplied by a variable raised to a
non-negative integer power. The variable typically
denoted as x, and the general form of a single
variable polynomial is:

P(x)=anxn+an−1xn−1+…+a1x+a0

where an,an−1,…,a1,a0 are constants called Introduction to Polynomials


coefficients, and n is a non-negative integer called In programming, it is essential to represent
the degree of the polynomial. polynomials in a structured manner to perform
operations such as addition, subtraction,
Now, let's discuss addition, subtraction, and multiplication, and evaluation.
multiplication of single variable polynomials:
Linked lists offer a more efficient and flexible
representation.
Addition of Polynomials:
Polynomial Representation
To add two polynomials, you simply combine like
Polynomial representation involves storing the
terms, which means you add or subtract the coefficients and exponents of each term in a
coefficients of terms with the same degree. polynomial.

In a linked list representation, each term is


represented as a node, which contains the
coefficient, exponent, and a pointer to the next node.
Consider the polynomial P(x) = 4x^3 + 9x^2 + 6x +
7.
To represent this polynomial using a linked list, we
would create nodes for each term as follows:
Node 1:
Subtraction of Polynomials: Coefficient: 4
Exponent: 3
Subtraction of polynomials is similar to addition. Next: Pointer to Node 2
You just need to distribute the negative sign and
then add the polynomials together. Node 2:
Coefficient: 9
Exponent: 2
Next: Pointer to Node 3

Node 3:
Coefficient: 6
Exponent: 1
Next: Pointer to Node 4

Node 4:
Coefficient: 7
Exponent: 0
Next: NULL

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 53
The linked list structure ensures that the terms are In this structure, the coefficient the variable
stored in descending order of their exponents. represents the numeric value of the term, while
the exponent variable denotes the power of the
This representation allows for efficient polynomial variable x. The next the pointer points to the next
operations, as we can easily traverse the linked list node in the linked list.
and perform computations on each term.
C Program to Add Two Polynomials using
Linked List: A Suitable Data Structure Linked List
In the context of polynomial representation, linked #include <stdio.h>
lists offer several advantages over other data #include <stdlib.h>
structures:
// Node structure for a term in the polynomial
Dynamic Memory Allocation: Linked lists allow for struct Node {
dynamic allocation of memory, enabling the int coefficient;
representation of polynomials with varying numbers int exponent;
of terms. This eliminates the need for fixed-size struct Node* next;
arrays and optimizes memory usage. };
struct Node* createTerm(int,int);
Efficient Insertion and Deletion: Linked lists provide struct Node* addTerm(struct Node*,int,int);
efficient insertion and deletion operations, as new struct Node* addPolynomials(struct Node*, struct
terms can be easily added or removed by adjusting Node*);
the pointers between nodes. This flexibility is void displayPolynomial(struct Node*);
particularly useful when performing polynomial void freePolynomial(struct Node*);
operations. int main()
{
Variable-Length Storage: Linked lists can store struct Node* poly1 = NULL;
polynomials of any length, accommodating struct Node* poly2 = NULL;
polynomials with varying numbers of terms. This
flexibility is crucial when dealing with sparse // Adding terms to the first polynomial
polynomials, where most terms have a coefficient of poly1 = addTerm(poly1, 3, 2);//3x^2
zero. poly1 = addTerm(poly1, 4, 1);//4x^1
poly1 = addTerm(poly1, 5, 0);//5x^0
Simplified Representation: Linked lists simplify the
polynomial representation by storing only the non- // Adding terms to the second polynomial
zero terms. This reduces memory requirements and poly2 = addTerm(poly2, 2, 2);//2x^2
allows for efficient traversal and computation on the poly2 = addTerm(poly2, 1, 1);//1x^1
terms. poly2 = addTerm(poly2, 7, 0);//7x^0

Overall, linked lists offer a versatile and efficient // Displaying the input polynomials
data structure for representing and manipulating printf("First Polynomial: ");
polynomials in programming. displayPolynomial(poly1);

Node Structure for Polynomial Representation printf("Second Polynomial: ");


In C programming, the representation of a node in a displayPolynomial(poly2);
polynomial linked list requires a structure that can
hold the coefficient, exponent, and a pointer to the // Performing addition
next node. struct Node* result = addPolynomials(poly1,
The structure can be defined as follows: poly2);
struct Node {
int coefficient; // Displaying the result
int exponent; printf("\nSum of the Polynomials: ");
struct Node* next; displayPolynomial(result);
};

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 54
// Freeing allocated memory // Change the sign(-) you`ll get subtraction
freePolynomial(poly1); program
freePolynomial(poly2); // Change the sign(*) you`ll get multiplication
freePolynomial(result); program

return 0; result = addTerm(result, sumCoeff, exp1);


} // Assuming both polynomials are in the same
variable (x)
// Function to create a new term node
struct Node* createTerm(int coefficient, int poly1 = poly1->next;
exponent) poly2 = poly2->next;
{
struct Node* newNode = (struct }
Node*)malloc(sizeof(struct Node));
newNode->coefficient = coefficient; return result;
newNode->exponent = exponent; }
newNode->next = NULL;
return newNode; // Function to display a polynomial linked list
} void displayPolynomial(struct Node* poly)
{
// Function to add a term to the polynomial linked while (poly != NULL) {
list printf("%dx^%d", poly->coefficient, poly-
struct Node* addTerm(struct Node* poly, int >exponent);
coefficient, int exponent) if (poly->next != NULL) {
{ printf(" + ");
struct Node* newNode = createTerm(coefficient, }
exponent); poly = poly->next;
if (poly == NULL) }
{ printf("\n");
return newNode; }
}
// Function to free the memory allocated for a
struct Node* current = poly; polynomial linked list
while (current->next != NULL) void freePolynomial(struct Node* poly) {
{ struct Node* current = poly;
current = current->next; struct Node* nextNode;
}
current->next = newNode; while (current != NULL) {
nextNode = current->next;
return poly; free(current);
} current = nextNode;
}
// Function to add two single-variable }
polynomials represented as linked lists
struct Node* addPolynomials(struct Node* poly1,
struct Node* poly2)
{
struct Node* result = NULL;

while (poly1 != NULL || poly2 != NULL)


{
int sumCoeff = coeff1 + coeff2;

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 55
Advantages of Linked List for Polynomial Dynamic Size: Linked lists can accommodate
Operations polynomials of any size, as they allow for dynamic
Using linked lists for polynomial representation and memory allocation. This flexibility eliminates the
operations offers several advantages over other data need for fixed-size arrays and optimizes memory
structures: usage.

Memory Efficiency: Linked lists only allocate Easy Insertion and Deletion: Linked lists provide
memory for non-zero terms, resulting in efficient straightforward insertion and deletion operations,
memory usage. This is particularly beneficial for allowing for efficient modification of polynomials.
sparse polynomials, where most terms have a New terms can be easily added or removed by
coefficient of zero. adjusting the pointers between nodes.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 56
Questions || Unit-2

1. What do you mean by Data Structure? Explain different types of DS.


2. Explain Singly Linked List. Assume a SLL [11⇒22⇒33⇒44⇒55⇒66⇒77] and perform following
operations-(Include explanation of steps using diagram and C program)
a. Traversal: Print the SLL.
b. Insertion: Insert 99 at position 4.
c. Deletion: Delete 5th element.
d. Search & Update: search any number given by the user and replace it with 66.
3. Explain Doubly Linked List. Assume a DLL [11=22=33=44=55=66=77] and perform following
operations-(Include explanation of steps using diagram and C program)
a. Traversal: Print the DLL from beginning and from end as well.
b. Insertion: Insert 99 at position 4.
c. Deletion: Delete 6th element.
d. Search & Update: Search any number given by the user and replace it with 88.
4. Explain Circular Singly Linked List. Assume a CSLL [11⇒22⇒33⇒44⇒55⇒66⇒77] and perform
following operations-(Include explanation of steps using diagram and C program)
a. Traversal: Print the CSLL.
b. Insertion: Insert 99 at position 4.
c. Deletion: Delete 5th element.
d. Search & Update: Search any number given by the user and replace it with 99.
5. Explain Polynomial Representation and Addition of Single variable Polynomials with examples

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 57
Lecture Notes || Unit -3
Syllabus:
Stacks: Abstract Data Type, Primitive Stack operations: Push & Pop, Array and Linked Implementation of Stack in C,
Application of stack: Prefix and Postfix Expressions, Evaluation of postfix expression, Recursion Queues: Operations
on Queue: Create, Add, Delete, Full and Empty, Circular queues, Array and linked implementation of queues in C,
Dequeue and Priority Queue

[T-10] Stacks

What is a Stack?
A Stack is a linear data structure that follows
the LIFO (Last-In-First-Out) principle. Stack has one
end, whereas the Queue has two ends (front and rear).
It contains only one pointer top pointer pointing to the
topmost element of the stack. In other words, a stack
can be defined as a container in which insertion and
deletion can be done from the one end known as the
top of the stack.
Since our stack is full as the size of the stack is 5. In
the above cases, we can observe that it goes from the
top to the bottom when we were entering the new
element in the stack. The stack gets filled up from the
bottom to the top.

When we perform the delete operation on the stack,


there is only one way for entry and exit as the other
end is closed. It follows the LIFO pattern, which
means that the value entered first will be removed
last. In the above case, the value 5 is entered first, so
it will be removed only after the deletion of all the
Some key points related to stack other elements.
o It is called as stack because it behaves like a
real-world stack, piles of books, etc. Standard Stack Operations
o A Stack is an abstract data type with a pre- The following are some common operations
defined capacity, which means that it can implemented on the stack:
store the elements of a limited size.
o It is a data structure that follows some order o push(): When we insert an element in a stack
to insert and delete the elements, and that then the operation is known as a push. If the
order can be LIFO or FILO. stack is full then the overflow condition
occurs.
Working of Stack o pop(): When we delete an element from the
Stack works on the LIFO pattern. As we can observe stack, the operation is known as a pop. If the
in the below figure there are five memory blocks in stack is empty means that no element exists
the stack; therefore, the size of the stack is 5. in the stack, this state is known as an
underflow state.
Suppose we want to store the elements in a stack and o isEmpty(): It determines whether the stack is
let's assume that stack is empty. We have taken the empty or not.
stack of size 5 as shown below in which we are o isFull(): It determines whether the stack is
pushing the elements one by one until the stack full or not.'
becomes full. o peek(): It returns the element at the given
position.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 58
o count(): It returns the total number of else
elements available in a stack. {
o change(): It changes the element at the given printf("Could not retrieve data, Stack is
position. empty.\n");
o display(): It prints all the elements available }
in the stack. }

Implementation of Stack: /* Function to insert into the stack */


There are two ways to implement a stack – int push(int data)
1. Stack Implementation in C using Array {
2. Stack Implementation in C using Linked List if(!isfull())
{
Method 1: top = top + 1;
(Stack Implementation in C using Array) stack[top] = data;
} else
#include <stdio.h> {
int MAXSIZE = 8; printf("Could not insert data, Stack is full.\n");
int stack[8]; }
int top = -1; }
/* Check if the stack is empty */
int isempty() /* Main function */
{ int main(){
if(top == -1) push(44);
return 1; push(10);
else push(62);
return 0; push(123);
} push(15);
/* Check if the stack is full */ printf("Element at top of the stack: %d\n" ,peek());
int isfull() printf("Elements: \n");
{ // print stack data
if(top == MAXSIZE) while(!isempty())
return 1; {
else int data = pop();
return 0; printf("%d\n",data);
} }
printf("Stack full: %s\n" , isfull()?"true":"false");
printf("Stack empty: %s\n" ,
/* Function to return the topmost element in the isempty()?"true":"false");
stack */ return 0;
int peek() }
{
return stack[top];
}

/* Function to delete from the stack */


int pop()
{
int data;
if(!isempty())
{
data = stack[top];
top = top - 1;
return data;
}

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 59
push() Function:

Example: Inserting a node with data 89

Pop() Method:
It removes an element from the top of the stack if the
stack is not empty. After removing the element, the
top is decremented by one.
Example: Pop out the data from the stack. However, a Linked List is a much more flexible data
structure. Both the push and pop operations can be
performed on either end. But We prefer performing
the Push and pop operation at the beginning.
Let us consider a linked list as shown here.
In the given data we can see that we have-
• Head = 200.
• Top = 33.

Peek() Method
It is used to show the top element of the non-empty
stack. The top is not decremented in this case.
Example: Peeking at the top element of the stack.

Push / Pop At the end Of a Linked List


Consider the Linked List as shown above. Now if
we want to push/pop a node at the end, we have to
traverse all the n number of nodes, until we reach the
Method 2: end of the linked list.
(Stack Implementation using Linked List) We traverse the whole list from the beginning to the
Stack can also be represented by using a linked list. end.
We know that in the case of arrays we face a
limitation, i.e , array is a data structure of limited size.

Hence before using an array to represent a stack, we


will have to consider an enough amount of space to
suffice the memory required by the stack.

Here, we insert and delete the nodes from the


beginning to perform the push and pop operation
respectively.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 60
Now if we want to insert a node at the end of the
linked list, we traverse from the first node to the //make the new node as head node so that head
second node to the last node. will always point the last inserted data
head = newNode;
We find the end of the list where the node points to }
the null and the node to be inserted is as shown
here. void pop()
{
//temp is used to free the head node
struct Node *temp;

if(head == NULL)
printf("Stack is Empty\n");
else
{
printf("Poped element = %d\n", head->data);

//backup the head node


temp = head;

The new node is pushed at the end of the list. //make the head node points to the next
The second last node , i.e, 08 now points to the node.logically removing the node
location of the last node. head = head->next;
The newly inserted node at the end now points
to null. //free the poped element's memory
free(temp);
}
}

//print the linked list


void display()
{
struct Node *temp = head;

//iterate the entire linked list and print the data


while(temp != NULL)
#include<stdio.h>
{
#include<stdlib.h>
printf("%d->", temp->data);
struct Node
temp = temp->next;
{ }
int data;
printf("NULL\n");
struct Node *next; }
};
int main()
struct Node *head = NULL; {
push(10);
void push(int val) push(20);
{
push(30);
//create new node printf("Linked List\n");
struct Node *newNode = malloc(sizeof(struct display();
Node));
pop();
newNode->data = val;
printf("After the pop, the new linked list\n");
display();
//make the new node points to the head node pop();
newNode->next = head;

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 61
printf("After the pop, the new linked list\n"); Application of Stack in real life:
display(); • CD/DVD stand.
• Stack of books in a book shop.
return 0; • Call center systems.
} • Undo and Redo mechanism in text editors.
• The history of a web browser is stored in the form
of a stack.
• Call logs, E-mails, and Google photos in any
gallery are also stored in form of a stack.
• YouTube downloads and Notifications are also
shown in LIFO format (the latest appears first).
• Allocation of memory by an operating system
while executing a process.

Advantages of Stack:
• Easy implementation: Stack data structure is
easy to implement using arrays or linked lists, and
its operations are simple to understand and
Application of Stack Data Structure: implement.
• Efficient memory utilization: Stack uses a
• Function calls and recursion: When a function contiguous block of memory, making it more
is called, the current state of the program is efficient in memory utilization as compared to
pushed onto the stack. When the function returns, other data structures.
the state is popped from the stack to resume the • Fast access time: Stack data structure provides
previous function’s execution. fast access time for adding and removing
• Undo/Redo operations: The undo-redo feature elements as the elements are added and removed
in various applications uses stacks to keep track from the top of the stack.
of the previous actions. Each time an action is • Helps in function calls: Stack data structure is
performed, it is pushed onto the stack. To undo used to store function calls and their states, which
the action, the top element of the stack is popped, helps in the efficient implementation of recursive
and the reverse operation is performed. function calls.
• Expression evaluation: Stack data structure is • Supports backtracking: Stack data structure
used to evaluate expressions in infix, postfix, and supports backtracking algorithms, which are used
prefix notations. Operators and operands are in problem-solving to explore all possible
pushed onto the stack, and operations are solutions by storing the previous states.
performed based on the stack’s top elements. • Used in Compiler Design: Stack data structure
• Browser history: Web browsers use stacks to is used in compiler design for parsing and syntax
keep track of the web pages you visit. Each time analysis of programming languages.
you visit a new page, the URL is pushed onto the • Enables undo/redo operations: Stack data
stack, and when you hit the back button, the structure is used to enable undo and redo
previous URL is popped from the stack. operations in various applications like text
• Balanced Parentheses: Stack data structure is editors, graphic design tools, and software
used to check if parentheses are balanced or not. development environments.
An opening parenthesis is pushed onto the stack,
and a closing parenthesis is popped from the Disadvantages of Stack:
stack. If the stack is empty at the end of the • Limited capacity: Stack data structure has a
expression, the parentheses are balanced. limited capacity as it can only hold a fixed
• Backtracking Algorithms: The backtracking number of elements. If the stack becomes full,
algorithm uses stacks to keep track of the states adding new elements may result in stack
of the problem-solving process. The current state overflow, leading to the loss of data.
is pushed onto the stack, and when the algorithm • No random access: Stack data structure does
backtracks, the previous state is popped from the not allow for random access to its elements, and
stack. it only allows for adding and removing elements
from the top of the stack. To access an element in

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 62
the middle of the stack, all the elements above it • Stack overflow and underflow: Stack data
must be removed. structure can result in stack overflow if too many
• Memory management: Stack data structure elements are pushed onto the stack, and it can
uses a contiguous block of memory, which can result in stack underflow if too many elements are
result in memory fragmentation if elements are popped from the stack.
added and removed frequently. • Recursive function calls limitations: While
• Not suitable for certain applications: Stack stack data structure supports recursive function
data structure is not suitable for applications that calls, too many recursive function calls can lead
require accessing elements in the middle of the to stack overflow, resulting in the termination of
stack, like searching or sorting algorithms. the program.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 63
[T-11] Application of stack: Prefix and Postfix 3.When we encounter any operator in the expression,
Expressions, Evaluation of postfix expression then we pop the corresponding operands from the
stack.
What is infix notation? 4.When we finish with the scanning of the expression,
When the operator is written in between the operands, the final value remains in the stack.
then it is known as infix notation. Let's understand the evaluation of postfix expression
For example, using stack.
(p + q) * (r + s) Example 1: Postfix expression: 2 3 4 * +
In the above expression, both the expressions of the
multiplication operator are the operands, i.e., (p + q),
and (r + s) are the operands. Input Stack
If there are multiple operators in the expression, then
some rule needs to be followed to evaluate the 234*+ empty Push 2
expression.
If the expression is: 34*+ 2 Push 3
4+6*2
If the plus operator is evaluated first, then the
4*+ 32 Push 4
expression would look like:
10 * 2 = 20
If the multiplication operator is evaluated first, then *+ 432 Pop 4 and 3, and perform 4*3 =
the expression would look like: 12. Push 12 into the stack.
4 + 12 = 16
Problem with infix expression is :To evaluate the + 12 2 Pop 12 and 2 from the stack, and
infix expression, we should know about the operator perform 12+2 = 14. Push 14 into
precedence rules, and if the operators have the same the stack.
precedence, then we should follow
the associativity rules. The result of the above expression is 14.
Prefix and postfix both expressions do not require Example 2: Postfix expression: 3 4 * 2 5 * +
any parenthesis and can be parsed without
ambiguity. It does not require operator
precedence and associativity rules. Input Stack

34*25 empty Push 3


*+

4*25* 3 Push 4
+

*2 5 * + 43 Pop 3 and 4 from the stack and


perform 3*4 = 12. Push 12 into
the stack.
Postfix Expression
The postfix expression is an expression in which the 25*+ 12 Push 2
operator is written after the operands.
For example, the postfix expression of infix notation 5*+ 2 12 Push 5
( 2+3) can be written as 23+.
*+ 5 2 12 Pop 5 and 2 from the stack and
We do not need to apply operator precedence rules perform 5*2 = 10. Push 10 into
and associativity rules. the stack.

Evaluation of postfix expression using stack. + 10 12 Pop 10 and 12 from the stack
1.Scan the expression from left to right. and perform 10+12 = 22. Push
2.If we encounter any operand in the expression, then 22 into the stack.
we push the operand in the stack.
The result of the above expression is 22.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 64
Conversion of infix to postfix
Rules for the conversion from infix to postfix
expression

1. Print the operand as they arrive.


2. If the stack is empty or contains a left
parenthesis on top, push the incoming
operator on to the stack.
3. If the incoming symbol is '(', push it on to the
stack.
4. If the incoming symbol is ')', pop the stack
and print the operators until the left
parenthesis is found.
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 lower precedence
than the top of the stack, pop and print the top
of the stack. Then test the incoming operator
against the new top of the stack.
7. If the incoming operator has the same
precedence with the top of the stack, then use
the associativity rules. If the associativity is
from left to right then pop and print the top of
the stack then push the incoming operator. If
the associativity is from right to left then push
the incoming operator.
8. At the end of the expression, pop and print all
the operators of the stack.

Let's understand through an example.


The final postfix expression of infix expression (K +
Infix expression:
L - M*N + (O^P) * W/U/V * T + Q) is KL+MN*-
K + L - M*N + (O^P) * W/U/V * T + Q
OP^W*U/V/T*+Q+.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 65
What is Prefix notation? Conversion of Prefix to Postfix expression
It is also known as polish notation. In prefix notation, Before understanding the conversion of prefix to
an operator comes before the operands. postfix conversion, lets revise the prefix and postfix
expressions separately.
For example, if the infix expression is 5+1, then the
prefix expression corresponding to this infix Let's understand the evaluation of postfix
expression is +51. expression using stack through an example.

Conversion of Infix to Prefix using Stack If the expression is: 5, 6, 2, +, *, 12, 4, /, -


Let convert:K + L - M * N + (O^P) * W/U/V * T + Q
to prefix expression.
If we are converting the expression from infix to
prefix,
we need first to reverse the expression.
The Reverse expression would be:
Q + T * V/U/W * ) P^O(+ N*M - L + K

When we encounter any symbol, we simply add it


into the prefix expression. If we encounter the
operator, we will push it into the stack.

The result of the above expression is 37.

Let's understand the evaluation of prefix expression


through an example.
Expression: +, -, *, 2, 2, /, 16, 8, 5
First, we will reverse the expression given above.
Expression: 5, 8, 16, /, 2, 2, *, -, +
We will use the stack data structure to evaluate the
prefix expression.

The final result of the above expression is 7.

The above expression, i.e.,


QTVUWPO^*//*NM*LK+-++, is not a final
expression. We need to reverse this expression to
obtain the prefix expression.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 66
Now, Rules for prefix to postfix expression using Conversion of Postfix to Prefix expression using
stack data structure: Stack
The following are the steps used to convert postfix
o Scan the prefix expression from right to left, to prefix expression using stack:
i.e., reverse. o Scan the postfix expression from left to
o If the incoming symbol is an operand, then right.
push it into the stack. o If the element is an operand, then push it
o If the incoming symbol is an operator, then into the stack.
pop two operands from the stack. Once the o If the element is an operator, then pop two
operands are popped out from the stack, we operands from the stack. Create an
add the incoming symbol after the operands. expression by concatenating two operands
When the operator is added after the and adding operator before the operands.
operands, then the expression is pushed back Push the result back to the stack.
into the stack. o Repeat the above steps until we reach the
o Once the whole expression is scanned, pop end of the postfix expression.
and print the postfix expression from the
stack. Let's understand the conversion of postfix to
prefix expression using stack.
Let's understand the conversion of Prefix to Postfix If the Postfix expression is given as:
expression using Stack through an example. AB + CD - *

If the expression is: * - A / B C - / A K L

The prefix expression of the above postfix


expression is *+AB-CD.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 67

You might also like