Unit 1
Unit 1
Information
information is the result of analyzing and interpreting pieces of data. Whereas data is the individual
figures, numbers, or graphs, information is the perception of those pieces of knowledge.
when the data is organized and compiled in a useful way can it provide information that is beneficial to
others.
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,
Rohland Gail, 34, F,
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
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.
Data type
A data type is a classification of data which tells the compiler or interpreter how the programmer
intends to use the data. Most programming languages support various types of data, including integer,
float, character or string, and Boolean.
Or
1. Data type defines a certain domain of values
2. Defines operations allowed on those values.
Example: int type
Takes only integer values
Operations add sub mul bitwise operations etc
Abstract Data Type (ADT)- ADT is a mathematical model that logically represents a datatype. ADT
only tells us the essential features without including background details. It specifies set of data and set of
operation that can be performed on the data. Example: List adt, Stack adt. Queue adt..
Data structure
A data structure is a way of organizing and storing data in a computer so that it can be accessed and used
efficiently. It refers to the logical or mathematical representation of data, as well as the implementation
in a computer program. Data structures are normally divided into two broad categories
Algorithm: An algorithm is well-defined steps by step procedure that take some value or set of
values as input and produce some value or set of values as output.
it must have the following characteristics:
• Clear and Unambiguous: The algorithm should be unambiguous. Each of its steps should be clear
in all aspects and must lead to only one meaning.
• Well-defined inputs: If an algorithm says to take inputs, it should be well-defined inputs. It may or
may not take input.
• Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it
should be well-defined as well. It should produce at least 1 output.
• Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
• Feasible: The algorithm must be simple, generic, and practical, such that it can be executed with
the available resources. It must not contain some future technology or anything.
• Language Independent: The Algorithm designed must be language-independent, i.e. it must be
just plain instructions that can be implemented in any language, and yet the output will be the same, as
expected.
• Input: An algorithm has zero or more inputs. Each that contains a fundamental operator must
accept zero or more inputs.
• Output: An algorithm produces at least one output. Every instruction that contains a fundamental
operator must accept zero or more inputs.
• Definiteness: All instructions in an algorithm must be unambiguous, precise, and easy to interpret.
By referring to any of the instructions in an algorithm one can clearly understand what is to be done.
Every fundamental operator in instruction must be defined without any ambiguity.
• Finiteness: An algorithm must terminate after a finite number of steps in all test cases. Every
instruction which contains a fundamental operator must be terminated within a finite amount
of time. Infinite loops or recursive functions without base conditions do not possess
finiteness.
• Effectiveness: An algorithm must be developed by using very basic, simple, and feasible
operations so that one can trace it out by using just paper and pencil.
Complexity:
Complexity of an algorithm Is a function of size of input of a given problem. Instance, which determines
how much running time oblique space is needed by the algorithm in order to run to compilation.
Time complexity: time complexity of an algorithm is the amount of time it needs in order to run to
compilation.
Space complexity: space complexity of an algorithm is the amount of space it needs in order to run to
compilation.
Algorithm Efficiency
The efficiency of an algorithm is mainly defined by two factors i.e. space and time. A good algorithm
is one that is taking less time and less space, but this is not possible all the time. There is a trade -off
between time and space. If you want to reduce the time, then space might increase. Similarly, if you
want to reduce the space, then the time may increase. So, you have to compromise with either space or
time. Let's learn more about space and time complexity of algorithms.
Asymptotic notations
The word Asymptotic means approaching a value or curve arbitrarily closely (i.e., as some sort of limit
is taken).
Asymptotic notations are used to write fastest and slowest possible running time for an algorithm.
These are also referred to as 'best case' and 'worst case' scenarios respectively.
"In asymptotic notations, we derive the complexity concerning the size of the input. (Example in terms
of n)"’ "These notations are important because without expanding the cost of running the algorithm, we
can estimate the complexity of the algorithms."
Big-oh-notation (O): It provides possibly asymptotically tight upper bound per f(n) and it does not give
best case complexity but can give worst case complexity.
Let f be a nonnegative function. Then we define the three most common asymptotic bounds as fallows.
We say that f(n) is Big-oh of g(n) written as f(n) = O(g(n)). iff there are positive constant c and n0 such
that 0≤f(n)≤cg(n) for all n ≥n0.
Big- Omega Notation(Ω): It provides possibly asymptotically tight lower bound for f(n) and it does not
give worst case complexity but can give best case complexity.
f(n) is said to be big-Omega of g(n) written as f(n)= Ω(g(n)), if there are positive constant c and n0, such
that 0 ≤cg(n) ≤f(n) for all n≥ n0.
Big Theta Notation (Ɵ): We say that f(n) is Big Theta of g(n), written as f(n) = Ɵ (g(n)). If there are
positive constants, c1,c2 and n0 such that 0 ≤c1g(n) ≤f(n) ≤ c2g(n) for all n≥ n0.
Equivalently f(n) = Ɵ( g(n)_ if and only if f(n) = O (g(n)) and f(n) = Ω (g(n)). If f(n) = Ɵ( g(n)) we say
that g(n) s a tight bound on f(n).
A BRIEF DESCRIPTION OF DATA STRUCTURES
1.8.1 Array
The simplest type of data structure is a linear (or one dimensional) array. A list of a finite number n of
similar data referenced respectively by a set of n consecutive numbers, usually 1, 2, 3 . . . . . . . n. if we
choose the name A for the array, then the elements of A are denoted by subscript notation
A 1, A 2, A 3 . . . . A n
or by the parenthesis notation
A (1), A (2), A (3) . . . . . . A (n)
or by the bracket notation
A [1], A [2], A [3] . . . . . . A [n]
Example:
A linear array A[8] consisting of numbers is pictured in following figure.
1.8.4 Graph
Data sometimes contains a relationship between pairs of elements which is not necessarily hierarchical
in nature, e.g. an airline flights only between the cities connected by lines. This data structure is called
Graph.
1.8.5 Queue
A queue, also called FIFO system, is a linear list in which deletions can take place only at one end of the
list, the Font of the list and insertion can take place only at the other end Rear.
1.8.6 Stack
It is an ordered group of homogeneous items of elements. Elements are added to and removed from the
top of the stack (the most recently added items are at the top of the stack). The last element to be added
is the first to be removed (LIFO: Last In, First Out).
• Traversing: accessing each record/node exactly once so that certain items in the record may be
processed. (This accessing and processing is sometimes called “visiting” the record.)
• Searching: Finding the location of the desired node with a given key value, or finding the
locations of all such nodes which satisfy one or more conditions.
• Inserting: Adding a new node/record to the structure.
Deleting: Removing a node/record from the structure
Array
An array is a list of a finite number ‘n’ of homogeneous data element such that The elements of the array
are reference respectively by an index set consisting of n consecutive numbers.
The element of the array are respectively in successive memory locations. The number n of elements is
called the length or size of the array. The length or the numbers of elements of the array can be obtained
from the index set by the formula When LB = 0,
Length = UB – LB + 1
When LB = 1,
Length = UB
Where,
UB is the largest index called the Upper Bound
LB is the smallest index, called the Lower Bound
Let LA be a linear array in the memory of the computer. The memory of the computer is simply a
sequence of address location as shown below,
1000
1001
1002
1003
1004
LOC (LA [K]) = address of the element LA [K] of the array LA. The elements of LA are stored in
successive memory cells.
The computer does not keep track of the address of every element of LA, but needs to keep track
only the address of the first element of LA denoted by, LA[0]
Using the base address of LA, the computer calculates the address of any element of LA by the formula
ARRAY OPERATIONS
1. Traversing
Let A be a collection of data elements stored in the memory of the computer. Suppose if the contents
of the each elements of array A needs to be printed or to count the numbers of elements of A with a
given property can be accomplished by Traversing.
Traversing is a accessing and processing each element in the array exactly once.
Program:
#include<stdio.h>
#include<conio.h> int
main()
{
int A[100],K=0,UB;
printf(“Enter the Array size less than 100: “);
printf(“Enter the elements in array: \n”);
for(K=0;K<UB;K++)
{
scanf(“%d”,&A[K]);
}
printf(“The Traverse of array is:\n”);
for(K=0;K<UB;K++)
{
printf(“%d\n”,A[K]);
}
getch();
return 0;
}
2. Inserting
Program:
#include <stdio.h>
int main()
{
int array[100], position, c, n, value; printf("Enter number
of elements in array\n"); scanf("%d", &n);
printf("Enter %d elements\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the location where you wish to insert an element\n");
scanf("%d", &position);
printf("Enter the value to insert\n");
scanf("%d", &value);
for (c = n - 1; c >= position - 1; c--)
array[c+1] = array[c];
array[position-1] = value;
printf("Resultant array is\n");
for (c = 0; c <= n; c++)
printf("%d\n", array[c]);
return 0;
}.
Deleting
➢ Deleting refers to the operation of removing one element to the collection A.
➢ Deleting an element at the “end” of the linear array can be easily done with difficulties.
➢ If element at the middle of the array needs to be deleted, then each subsequent elements be
moved one location upward to fill up the array.
Algorithm
program
#include <stdio.h>
int main()
{
int array[100], position, c, n;
printf("Enter number of elements in array\n"); canf("%d", &n);+
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the location where you wish to delete element\n");
scanf("%d", &position);
if (position >= n+1)
printf("Deletion not possible.\n");
else
{
for (c = position - 1; c < n - 1; c++)
array[c] = array[c+1];
printf("Resultant array:\n");
for (c = 0; c < n - 1; c++)
printf("%d\n", array[c]);
}
return 0;
}
Multidimensional Arrays
In C, we can define multidimensional arrays in simple words as array of arrays. Data in
multidimensional arrays are stored in tabular form (in row-major order). General form of declaring N-
dimensional arrays:
data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array. Here data_type is valid C data type
array_name: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions
Examples:
Ouput:
1. Column-Major Order:
In this method the elements are stored column wise, i.e. m elements of first column are stored in first m
locations, m elements of second column are stored in next m locations and so on. E.g.
A 3 x 4 array will stored as below:
2. Row-Major Order:
In this method the elements are stored row wise, i.e. n elements of first row are stored in first n
locations, n elements of second row are stored in next n locations and so on. E.g.
A 3 x 4 array will stored as below:
Address of an element of any array say “A[ I ][ J ]” is calculated in two forms as given:
The address of a location in Column Major System is calculated using the following formula:
Address of A [ I ][ J ] Column Major Wise = BA + W * [( I – Lr ) + M * ( J – Lc )] Where,
B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found W = Storage Size of one element stored
in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
M = Number of rows of the given matrix
N = Number of columns of the given matrix.
1-D array
2-D array
To find the address of any element in a 2-Dimensional array there are the following two ways-
1. Row Major Order
2. Column Major Order
1. 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] = BA + 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.
Example: 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))
Solution:
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
Example: 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] = BA + 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
From the above examples, it can be observed that for the same position two different address locations
are obtained that’s because in row-major order movement is done across the rows and then down to the
next row, and in column-major order, first move down to the first column and then next column. So both
the answers are right.
So it’s all based on the position of the element whose address is to be found for some cases the same
answers is also obtained with row-major order and column-major order and for some cases, different
answers are obtained.
To find the address of any element in 3-Dimensional arrays there are the following two ways-
• Row Major Order
• Column Major Order
•
1. Row Major Order:
To find the address of the element using row-major order, use the following formula:
Address of A[i][j][k] = BA + W *(P * N * (i-x) +P *(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
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 A[i][j][k] = BA + W *(P * N * (i-x) +P *(j-y) + (k-z))
Solution:
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
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 = 8 -1+1 = 8
N (column)= Upper Bound – Lower Bound + 1 = 5 + 5 + 1 = 11
Formula used:
Address of A[i][j][k]= BA + W(M * N(k – z) + M *( j – y) + (i-x))
Solution:
Address of arr[3][3][3] = 400 + 4 * ((11*8*(3-1)+8*(3-(-5)+(3-(-10)))
= 400 + 4 * ((88*2 + 8*8 + 13)
= 400 + 4 * (253) = 400 + 1012 = 1412
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 }
};
int size = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
size++;
printf("\n");
}
return 0;
}
Initialization
malloc() allocates a memory block of given size (in bytes) and returns a pointer to the beginning of the
block. malloc() doesn’t initialize the allocated memory. If you try to read from the allocated memory
without first initializing it, then you will invoke undefined behavior, which usually means the values
you read will be garbage values
calloc() allocates the memory and also initializes every byte in the allocated memory to 0. If you try to
read the value of the allocated memory without initializing it, you’ll get 0 as it has already been
initialized to 0 by calloc().
Parameters
Return Value
After successful allocation in malloc() and calloc(), a pointer to the block of memory is returned
otherwise NULL is returned which indicates failure.
Difference between malloc() and calloc() in C
Linked List
A linked list is a non-sequential collection of data items. It is a dynamic data structure. For every data
item in a linked list, there is an associated pointer that would give the memory location of the next data
item in the linked list.
The data items in the linked list are not in consecutive memory locations. They may be anywhere, but
the accessing of these data items is easier as each data item contains the address of the next data item.
Advantages of linked lists:
Linked lists have many advantages. Some of the very important advantages are:
1. Linked lists are dynamic data structures. i.e., they can grow or shrink during the execution of a
program.
2. Linked lists have efficient memory utilization. Here, memory is not pre- allocated. Memory is
allocated whenever it is required and it is de- allocated (removed) when it is no longer needed.
3. Insertion and Deletions are easier and efficient. Linked lists provide flexibility in inserting a data item
at a specified position and deletion of the data item from the given position.
4. Many complex applications can be easily carried out with linked lists.
Disadvantages of linked lists:
1. It consumes more space because every node requires a additional pointer to store address of the next
node.
2. Searching a particular element in list is difficult and also time consuming.
Types of Linked Lists:
Basically we can put linked lists into the following four items:
1. Single Linked List.
2. Double Linked List.
3. Circular Linked List.
Single linked list is one in which all nodes are linked together in some sequential manne r. Hence, it is
also called as linear linked list.
A double linked list is one in which all nodes are linked togethe r by multiple links which helps in
accessing both the successor node (next node) and predeces sor node (previous node) from any arbitrary
node within the list. Therefore each node in a double linked list has two link fields (pointers) to point to
the left node (previous) and the right node (next). This helps to traverse in forward direction and
backward direction.
A circular linked list is one, which has no beginning and no end. A single linked list can be made a
circular linked list by simply storing address of the very first node in the link field of the last node.
The beginning of the linked list is stored in a " start " pointer which points to the first node. The first
node contains a pointer to the second node.
The second node contains a pointer to the third node, ... and so on. The last node in the list has its next
field set to NULL to mark the end of the list. Code can access any node in the list by starting at the start
and following the next pointers .
The start pointer is an ordinary local pointe r variable, so it is drawn separately on the left top to show
that it is in the stack. The list nodes are drawn on the right to show that they are allocated in the heap.
The basic operations in a single linked list are:
➢ Creation.
➢ Insertion.
➢ Deletion.
➢ Traversing.
Traversing a Linked List
Suppose we want to traverse LIST in order to process each node exactly once. The traversing algorithm
uses a pointer variable PTR which points to the node that is currently being processed. Accordingly,
PTR->NEXT points to the next node to be processed so,
Program
void search()
1. {
2. struct node *ptr;
3. int item,i=0,flag;
4. ptr = head;
5. if(ptr == NULL)
6. {
7. printf("\nEmpty List\n");
8. }
9. else
10. {
11. printf("\nEnter item which you want to search?\n");
12. scanf("%d",&item);
13. while (ptr!=NULL)
14. {
15. if(ptr->data == item)
16. {
17. printf("item found at location %d ",i+1);
18. flag=0;
19. }
20. else
21. {
22. flag=1;
23. }
24. i++;
25. ptr = ptr -> next;
26. }
27. if(flag==1)
28. {
29. printf("Item not found\n");
30. } } }
Creation of a node:
Creating a singly linked list starts with creating a node. Sufficient memory has to be allocated for
creating a node. The information is stored in the memory, allocated by using the malloc() function. after
allocating memory for the structure of type node, the information for the item (i.e., data) has to be read
from the user, set next field to NULL and finally returns the address of the node.
Creating a Singly Linked List with ‘n’ number of nodes:
The following steps are to be followed to create ‘n’ number of nodes:
• Get the new node using malloc();
• If the list is empty, assign new node as start. start = newnode;
• If the list is not empty, follow the steps given below:
• The next field of the new node is made to point the first node (i.e. start node) in the list by assigning
the address of the first node.
• The start pointer is made to point the new node by assigning the address of the new node.
• Repeat the above steps ‘n’ times.
Figure shows 4 items in a single linked list stored at different locations in memory.
Insertion of a Node:
One of the most primitive operations that can be done in a singly linked list is the insertion of a node.
Memory is to be allocated for the new node (in a similar way that is done while creating a list) before
reading the data. The new node will contain empty data field and empty next field. The data field of the
new node is then stored with the information read from the user. The next field of the new node is
assigned to NULL. The new node can then be inserted at three different places namely:
➢ Inserting a node at the beginning.
➢ Inserting a node at the end.
➢ Inserting a node at intermediate position.
Inserting a node at the beginning:
The following steps are to be followed to insert a new node at the beginning of the list:
➢ Get the new node using malloc().
➢ If the list is empty then start = newnode.
➢ If the list is not empty, follow the steps given below:
newnode -> next = start;
start = newnode;
Figure shows inserting a node into the single linked list at the beginning.
Algorithm: INSFIRSTBEG (INFO, NEXT, HEAD,ITEM)
This algorithm inserts ITEM as the first node in the list
Program
void beginsert()
1. {
2. struct node *ptr;
3. int item;
4. ptr = (struct node *) malloc(sizeof(struct node *));
5. if(ptr == NULL)
6. {
7. printf("\nOVERFLOW");
8. }
9. else
10. {
11. printf("\nEnter value\n");
12. scanf("%d",&item);
13. ptr->data = item;
14. ptr->next = head;
15. head = ptr;
16. printf("\nNode inserted");
17. } }
Figure shows inserting a node into the single linked list at the end.
Program:
void lastinsert()
1. {
2. struct node *ptr,*temp;
3. int item;
4. ptr = (struct node*)malloc(sizeof(struct node));
5. if(ptr == NULL)
6. {
7. printf("\nOVERFLOW");
8. }
9. else
10. {
11. printf("\nEnter value?\n");
12. scanf("%d",&item);
13. ptr->data = item;
14. if(head == NULL)
15. {
16. ptr -> next = NULL;
17. head = ptr;
18. printf("\nNode inserted");
19. }
20. else
21. {
22. temp = head;
23. while (temp -> next != NULL)
24. {
25. temp = temp -> next;
26. }
27. temp->next = ptr;
28. ptr->next = NULL;
29. printf("\nNode inserted");
30.
31. }
32. }
33. }
Inserting a node at ANY position:
The following steps are followed, to insert a new node in an intermediate position in the list:
➢ Get the new node using malloc().
➢ Ensure that the specified position is in between first node and last node. If not, specified position
is invalid..
➢ Store the starting address (which is in start pointer ) in temp and prev pointers . Then traverse
the temp pointer upto the specified position followed by prev pointer .
➢ After reaching the specified position, follow the steps given below:
prev -> next = newnode;
newnode -> next = temp;
➢ Let the intermediate position be 3.
.Figure shows inserting a node into the single linked list at a specified intermediate position other than
beginning and end.
Program:
void randominsert()
1. {
2. int i,loc,item;
3. struct node *ptr, *temp;
4. ptr = (struct node *) malloc (sizeof(struct node));
5. if(ptr == NULL)
6. {
7. printf("\nOVERFLOW");
8. }
9. else
10. {
11. printf("\nEnter element value");
12. scanf("%d",&item);
13. ptr->data = item;
14. printf("\nEnter the location after which you want to insert ");
15. scanf("\n%d",&loc);
16. temp=head;
17. for(i=0;i<loc;i++)
18. {
19. temp = temp->next;
20. if(temp == NULL)
21. {
22. printf("\ncan't insert\n");
23. return;
24. }
25. }
26. ptr ->next = temp ->next;
27. temp ->next = ptr;
28. printf("\nNode inserted");
29. }
30. }
Deletion of a node:
Another primitive operation that can be done in a singly linked list is the deletion of a node. Memory is
to be released for the node to be deleted. A node can be deleted from the list from three different places
namely.
➢ Deleting a node at the beginning.
➢ Deleting a node at the end.
➢ Deleting a node at intermediate position.
Deleting a node at the beginning:
The following steps are followed, to delete a node at the beginning of the list:
➢ If list is empty then display ‘Empty List’ message.
➢ If the list is not empty, follow the steps given below:
temp = star t ;
star t = star t -> next;
free(temp);
Figure shows deleting a node at the beginning of a single linked list.
Algorithm
Step 1: IF HEAD = NULL
Write UNDERFLOW
Go to Step 5
[END OF IF]
Step 2: SET PTR = HEAD
Step 3: SET HEAD = HEAD -> NEXT
Step 4: FREE PTR
Step 5: EXIT
Program:
void begin_delete()
1. {
2. struct node *ptr;
3. if(head == NULL)
4. {
5. printf("\nList is empty\n");
6. }
7. else
8. {
9. ptr = head;
10. head = ptr->next;
11. free(ptr);
12. printf("\nNode deleted from the begining ...\n");
13. } }
Algorithm
Step 1: IF HEAD = NULL
Write UNDERFLOW
Go to Step 8
[END OF IF]
Step 2: SET PTR = HEAD
Step 3: Repeat Steps 4 and 5 while PTR -> NEXT!= NULL
Step 4: SET TEMP = PTR
Step 5: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 6: SET TEMP -> NEXT = NULL
Step 7: FREE PTR
Step 8: EXIT
Program:
void last_delete()
1. {
2. struct node *ptr,*ptr1;
3. if(head == NULL)
4. printf("\nlist is empty");
5. else if(head -> next == NULL)
6. {
7. head = NULL;
8. free(head);
9. printf("\nOnly node of the list deleted ...\n");
10. }
11. else
12. {
13. ptr = head;
14. while(ptr->next != NULL)
15. {
16. ptr1 = ptr;
17. ptr = ptr ->next;
18. }
19. ptr1->next = NULL;
20. free(ptr);
21. printf("\nDeleted Node from the last ...\n");
22. } }
The following algorithm deletes a node from any position in the LIST.
Proogram:
void random_delete()
{
struct node *ptr,*ptr1;
int loc,i;
printf("\n Enter the location of the node after which you want to perform deletion \n");
scanf("%d",&loc);
ptr=head;
for(i=0;i<loc-1;i++)
{
ptr1 = ptr;
ptr = ptr->next;
if(ptr == NULL)
{
printf("\nCan't delete");
return;
}
}
ptr1 ->next = ptr ->next;
free(ptr);
printf("\nDeleted node %d ",loc+1);
}
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head=NULL;
}
}
}
void randominsert()
{
int i,loc,item;
struct node *ptr, *temp;
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter element value");
scanf("%d",&item);
ptr->data = item;
printf("\nEnter the location after which you want to insert ");
scanf("\n%d",&loc);
temp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\ncan't insert\n");
return;
}
}
ptr ->next = temp ->next;
temp ->next = ptr;
printf("\nNode inserted");
}
}
void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nList is empty\n");
}
else
{
ptr = head;
head = ptr->next;
free(ptr);
printf("\nNode deleted from the begining ...\n");
}
}
void last_delete()
{
struct node *ptr,*ptr1;
if(head == NULL)
{
printf("\nlist is empty");
}
else if(head -> next == NULL)
{
head = NULL;
free(head);
printf("\nOnly node of the list deleted ...\n");
}
else
{
ptr = head;
while(ptr->next != NULL)
{
ptr1 = ptr;
ptr = ptr ->next;
}
ptr1->next = NULL;
free(ptr);
printf("\nDeleted Node from the last ...\n");
}
}
void random_delete()
{
struct node *ptr,*ptr1;
int loc,i;
printf("\n Enter the location of the node after which you want to perform deletion \n");
scanf("%d",&loc);
ptr=head;
for(i=0;i<loc;i++)
{
ptr1 = ptr;
ptr = ptr->next;
if(ptr == NULL)
{
printf("\nCan't delete");
return;
}
}
ptr1 ->next = ptr ->next;
free(ptr);
printf("\nDeleted node %d ",loc+1);
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
flag=0;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("Item not found\n");
}
}
}
void display()
{
struct node *ptr;
ptr = head;
if(ptr == NULL)
{
printf("Nothing to print");
}
else
{
printf("\nprinting values . . . . .\n");
while (ptr!=NULL)
{
printf("\n%d",ptr->data);
ptr = ptr -> next;
}
}
}
The beginning of the double linked list is stored in a " start " pointe r which points to the first node. The
first node’s left link and last node’s right link is set to NULL. The following code gives the structure
definition:
struct dlinklist
{
struct dlinklist * left ;
int d at a;
struct dlinklist * right ;
};
Creating a node for Doubly Linked List:
Creating a double linked list starts with creating a node. Sufficient memory has to be allocated for
creating a node. The information is stored in the memory, allocated by using the malloc() function.
after allocating memory for the structure of type node, the information for the item (i.e., data) has
to be read from the user and set left field to NULL and right field also set to NULL
Creating a Doubly Linked List with ‘n’ number of nodes :
The following steps are to be followed to create ‘n’ number of nodes:
➢ Get the new node using malloc().
➢ If the list is empty then start = newnode.
➢ If the list is not empty, follow the steps given below:
➢ The left field of the new node is made to point the previous node.
➢ The previous nodes right field must be assigned with address of the new node.
➢ Repeat the above steps ‘n’ times.
Insertion:
Insertion of a Node at the beginning: The following steps are to be followed to insert a new
node at the beginning of the list:
• Get the new node using malloc().
• If the list is empty then start = newnode.
• If the list is not empty, follow the steps given below:
newnode -> right = start;
start -> left = newnode;
start = newnode;
Figure shows inserting a node into the double linked list at the beginning.
Figure shows inserting a node into the double linked list at the end.
ALGORITHM
Inserting a node at an intermediate position: The following steps are followed, to insert a new
node in an intermediate position in the list:
• Get the new node using malloc().
• Ensure that the specified position is in between first node and last node. If not, specified position is
invalid.
• Store the starting address (which is in start pointer) in temp and prev pointers. Then traverse the temp
pointer upto the specified position followed by prev pointer.
• After reaching the specified position, follow the steps given below:
newnode -> left = temp;
newnode -> right = temp -> right;
temp -> right -> left = newnode;
temp -> right = newnode;
Figure shows inserting a node into the double linked list at a specified intermediate position other than
beginning and end.
ALGORITHM
STEP 1: IF PTR = NULL
WRITE OVERFLOW
RETURN [ END OF IF]
STEP 2: SET NEW_NODE = PTR
STEP 3: SET NEW_NODE → INFO = ITEM
STEP 4: : SET NEW_NODE → NEXT = NULL
STEP 5: SET NEW_NODE → PREV = NULL
STEP 6: SET TEMP = HEAD
STEP 7: SET I = 0
STEP 8: REPEAT STEP 9 TO 11 UNTIL I<loc-1
STEP 9 SET TEMP1= TEMP
TEMP = TEMP → NEXT
STEP 10: IF TEMP = NULL
WRITE "DESIRED NODE NOT PRESENT"
RETURN
END OF IF
STEP 11: SET I = I+1
END OF LOOP
STEP 12: SET TEMP1 → NEXT → PREV = NEW_NODE
STEP 13: SET NEW_NODE → NEXT = TEMP1 → NEXT
STEP 14: SET TEMP1 → NEXT = NEW_NODE
STEP 15: SET NEW_NODE → PREV = TEMP1
STEP 16: EXIT
Deletion:
Deleting a node at the beginning: The following steps are followed, to delete a node at the beginning
of the list: • If list is empty then display ‘Empty List’ message.
• If the list is not empty, follow the steps given below:
temp = start;
start = start -> right;
start -> left = NULL;
free(temp);
Figure shows deleting a node at the beginning of a double linked list.
Algorithm
Step 1: IF HEAD = NULL
Write UNDERFLOW
RETURN
[END OF IF]
Step 2: SET PTR = HEAD
Step 3: SET HEAD = HEAD -> NEXT
Step 4: SET HEAD -> PREV = NULL
Step 5: FREE PTR
Step 6: EXIT
Deleting a node at the end: The following steps are followed to delete a node at the end of the list:
• If list is empty then display ‘Empty List’ message
• If the list is not empty, follow the steps given below:
temp = start;
while(temp -> right != NULL)
{ temp = temp -> right; }
temp -> left -> right = NULL;
free(temp);
Figure shows deleting a node at the end of a doubly linked list.
ALGORITHM
Step 1: IF HEAD = NULL
Write UNDERFLOW
RETURN [END OF IF]
Step 2: SET PTR = HEAD
Step 3: Repeat Steps 4 and 5 while PTR -> NEXT!= NULL
Step 4: SET TEMP = PTR
Step 5: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 6: SET TEMP -> NEXT = NULL:
Step 7: FREE PTR
Step 8: EXIT
Deleting a node at Intermediate position: The following steps are followed, to delete a node from an
intermediate position in the list (List must contain more than two nodes).
• If list is empty then display ‘Empty List’ message.
• If the list is not empty, follow the steps given below:
• Get the position of the node to delete.
• Ensure that the specified position is in between first node and last node. If not, specified position is
invalid.
• Then perform the following steps:
if(pos > 1 && pos < nodectr)
{ temp = start;
i = 1;
while(i < pos)
{ temp = temp -> right;
i+ +; }
temp -> right -> left = temp -> left;
temp -> left -> right = temp -> right;
free(tem p);
printf("\n node deleted.."); }
Figure shows deleting a node at a specified intermediate position other than beginning and end from a
doubly linked list.
ALGORITHM
STEP 1: IF HEAD = NULL
WRITE UNDERFLOW
RETURN
[END OF IF]
STEP 2: SET TEMP = HEAD
STEP 3: SET I = 0
STEP 4: REPEAT STEP 5 TO 8 UNTIL I<loc-1
STEP 5: TEMP1 = TEMP
STEP 6: TEMP = TEMP → NEXT
STEP 7: IF TEMP = NULL
WRITE "DESIRED NODE NOT PRESENT"
RETURN
END OF IF
STEP 8: I = I+1
END OF LOOP
STEP 9: TEMP1 → NEXT = TEMP → NEXT
STEP 10: TEMP1 → NEXT →PREV = TEMP1
STEP 11: FREE TEMP
STEP 12: EXIT
Traversal and displaying a list (Left to Right): To display the information, you have to traverse the
list, node by node from the first node, until the end of the list is reached. The following steps are
followed, to traverse a list from left to right:
• If list is empty then display ‘Empty List’ message.
• If the list is not empty, follow the steps given below:
temp = start;
while(tem p != NULL)
{ print temp -> data;
temp = temp -> right; }
Traversal and displaying a list (Right to Left): To display the information from right to left, you have
to traverse the list, node by node from the first node, until the end of the list is reached.
The following steps are followed, to traverse a list from right to left:
• If list is empty then display ‘Empty List’ message.
• If the list is not empty, follow the steps given below:
temp = start; while(tem p -> right != NULL)
temp = temp -> right;
while(tem p != NULL)
{ print temp -> data;
temp = temp->left;}
Complete Program for Doubly Link list
#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *prev;
struct node *next;
int data;
};
struct node *head;
void insertion_beginning();
void insertion_last();
void insertion_specified();
void deletion_beginning();
void deletion_last();
void deletion_specified();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
printf("\n*****Main Menu******\n");
printf("\nChoose one option from the following list ...\n");
printf("\n======\n");
printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4.Delete
from Beginning\n 5.Delete from last\n6.Delete the node after the given data\n7.Search\n8.
Show\n9.Exit\n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
insertion_beginning();
break;
case 2:
insertion_last();
break;
case 3:
insertion_specified();
break;
case 4:
deletion_beginning();
break;
case 5:
deletion_last();
break;
case 6:
deletion_specified();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void insertion_beginning()
{
struct node *ptr;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter Item value");
scanf("%d",&item);
if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
printf("\nNode inserted\n");
}
}
void insertion_last()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}
}
printf("\nnode inserted\n");
}
void insertion_specified()
{
struct node *ptr,*temp;
int item,loc,i;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{
temp=head;
printf("Enter the location");
scanf("%d",&loc);
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\n There are less than %d elements", loc);
return;
}
}
printf("Enter value");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
printf("\nnode inserted\n");
}
}
void deletion_beginning()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
head = head -> next;
head -> prev = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_specified()
{
struct node *ptr, *temp;
int val;
printf("\n Enter the data after which the node is to be deleted : ");
scanf("%d", &val);
ptr = head;
while(ptr -> data != val)
ptr = ptr -> next;
if(ptr -> next == NULL)
{
printf("\nCan't delete\n");
}
else if(ptr -> next -> next == NULL)
{
ptr ->next = NULL;
}
else
{
temp = ptr -> next;
ptr -> next = temp -> next;
temp -> next -> prev = ptr;
free(temp);
printf("\nnode deleted\n");
}
}
void display()
{
struct node *ptr;
printf("\n printing values...\n");
ptr = head;
while(ptr != NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("\nitem found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("\nItem not found\n");
}
} }
Circular Single Linked List:
It is just a single linked list in which the link field of the last node points back to the address of the first
node. A circular linked list has no beginning and no end. It is necessary to establish a special pointer
called start pointer always pointing to the first node of the list.
Circular linked lists are frequently used instead of ordinary linked list because many operations are much
easier to implement. In circular linked list no null pointers are used, hence all pointers contain valid
address. A circular single linked list is shown in figure .
Figure shows inserting a node into the circular single linked list at the end.
ALGORITHM
Step 1: IF PTR = NULL
Write OVERFLOW
RETURN [END OF IF]
Step 2: SET PTR -> INFO = ITEM
Step 3: SET PTR -> NEXT = NULL
Step 4: SET TEMP = HEAD
Step 5: Repeat Step 8 while TEMP -> NEXT != HEAD
Step 6: SET TEMP = TEMP -> NEXT
[END OF LOOP]
Step 7: SET TEMP -> NEXT = PTR
Step 8: SET PTR -> NEXT=HEAD
Step 9: EXIT
ALGORITHM
Step 1: IF HEAD = NULL
Write UNDERFLOW
RETURN
[END OF IF]
Step 2: SET PTR = HEAD
Step 3: Repeat Step 4 while PTR → NEXT != HEAD
Step 4: SET PTR = PTR → next
[END OF LOOP]
Step 5: SET PTR → NEXT = HEAD → NEXT
Step 6: FREE HEAD
Step 7: SET HEAD = PTR → NEXT
Step 8: EXIT
Algorithm
Step 1: IF HEAD = NULL
Write UNDERFLOW
RETURN
[END OF IF]
Step 2: SET PTR = HEAD
Step 3: Repeat Steps 4 and 5 while PTR -> NEXT != HEAD
Step 4: SET TEMP = PTR
Step 5: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 6: SET TEMP -> NEXT = HEAD
Step 7: FREE PTR
Step 8: EXIT
printf("\nnode inserted\n");
}
}
void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nUNDERFLOW");
}
else if(head->next == head)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{ ptr = head;
while(ptr -> next != head)
ptr = ptr -> next;
ptr->next = head->next;
free(head);
head = ptr->next;
printf("\nnode deleted\n");
}
}
void last_delete()
{
struct node *ptr, *preptr;
if(head==NULL)
{
printf("\nUNDERFLOW");
}
else if (head ->next == head)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
while(ptr ->next != head)
{
preptr=ptr;
ptr = ptr->next;
}
preptr->next = ptr -> next;
free(ptr);
printf("\nnode deleted\n");
}
}
void search()
{
struct node *ptr;
int item,i=0,flag=1;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
if(head ->data == item)
{
printf("item found at location %d",i+1);
flag=0;
}
else
{
while (ptr->next != head)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
}
if(flag != 0)
{
printf("Item not found\n");
}
}
}
void display()
{
struct node *ptr;
ptr=head;
if(head == NULL)
{
printf("\nnothing to print");
}
else
{
printf("\n printing values ... \n");
while(ptr -> next != head)
{
printf("%d\n", ptr -> data);
ptr = ptr -> next;
}
printf("%d\n", ptr -> data);
}
Abstract Data Type (ADT)- ADT is a mathematical model that logically represents a
datatype. ADT only tells us the essential features without including background details. It specifies set of
data and set of operation that can be performed on the data.
Example: List adt, Stack adt. Queue adt
P=LINK [P];
}}
Polynomial
A polynomial is a mathematical expression that contains more than two algebraic terms. It is a sum of
several terms that contain different powers of the same variable. p(x)is the representation of a
polynomial. A polynomial expression representation consists of at least one variable, and typically
includes constants and positive constants as well. It is represented as a1xn+ a2xn−1+a3xn−2+.............+anx0,
where x is the variable, (a1, a2,a3,....................,an)are the coefficients and n is the degree of the
polynomial. The coefficients must be a real number.
It is necessary for the polynomial expression that each expression consists of two parts:
1. Coefficient part
2. Exponent part
Example:
p(x) = 21x3 + 3x2 + 14x1 + 21x0 .Here, 21, 3, 14, and 21 are the coefficients, and 3,2,1 and 0 are the
exponential values x.
Types of polynomials
Monomial
It has only one term, like 2x, 23xy.
Binomial
It has two terms, or we can say that it is the sum of two monomials; for example, 2x+3.
Trinomial
It consists of three terms of monomials; for example, 2x+3y+7z.
Representation of polynomial
There are various ways to represent the polynomials, two of which are given below.
• Using array
• Using a linked list
•
Representation of polynomial equation using array
The operations such as addition, subtraction, multiplication, differentiation and so forth can be
performed on the polynomials represented as arrays.
Example:
Consider a polynomial with two variables: 2x2+5xy+y2. The array representation of the polynomial is
give below:
2 2 0 5 1 1 1 0 2
Index 0 stores the coefficient of the first term, index 1 stores the exponent of the variable x and index 2
stores the exponent of the variable y in the first term. The process is repeated for the remaining terms in
the polynomial. It can also be represented as a 2-dimentional array as follows:
y0 y1 y2
X0 0 0 1
x1 0 5 0
x2 2 0 0
Consider a polynomial −4+7x+6x2then we can write as: −4x0+7x1+6x2. . For the one-dimensional array,
store the coefficients in the index given by the coefficient of the polynomial.
Consider two different polynomials X1 = 3x1+5x2+7x3and X2= 7x0+3x1+4x2. The degree of X1is 3 and
the degree of X2 is 2. The steps to add the polynomials are listed below.
• First identify the highest degree polynomial. The degree of the resultant polynomial is same as
the polynomial with the highest degree.
• Store the coefficient in the index specified by the exponents of the polynomial.
• Add the coefficients stored in one array with the corresponding index positions in the other array
and store the result in the same index position in the resultant array.
An ordered list of non-zero terms can be thought of as a polynomial. Each non-zero term consists of
three sections namely coefficient part, exponent part, and then a pointer pointing to the node containing
the next term of the polynomial.
Let's take an example- If the polynomial is 2x2+3x+, then it is written in the form of 2x2+3x1+4x0 and
represented it using a linked list. In the diagram, AON means "address of next node".
The above diagram shows the array representation of polynomial. A polynomial of a single variable
A(X)can be written as a0+a1X1+a2X2+a3X3+.........+anXn where an≠0and degree of A(X) is n.
Here a0, a1, a2, ......an is the coefficient of respective terms.
.
To multiply two polynomials, we can first multiply each term of one polynomial to the other
polynomial. Suppose the two polynomials have and terms. This process will create a polynomial
with terms. For example, after we multiply 2-4x+5x2 and 1+2x-3x3, we can get a linked list:
This linked list contains all terms we need to generate the final result. However, it is not sorted by the
powers. Also, it contains duplicate nodes with like terms. To generate the final linked list, we can
first merge sort the linked list based on each node’s power:
After the sorting, the like term nodes are grouped together. Then, we can merge each group of like terms
and get the final multiplication result:
We can represent a polynomial with more than one variable, i.e., it can be two or three variables. Below
is a node structure suitable for representing a polynomial with three variables X, Y, Z using a singly
linked list.
Terms in such a polynomial are ordered accordingly to the decreasing degree in x. Those with the same
degree in x are ordered according to decreasing degree in y. Those with the same degree in x and y are
ordered according to decreasing degrees in z.
#include <stdio.h>
#include <stdlib.h>
if (*poly1 == NULL)
{
*poly1 = new;
} else {
struct node * current = *poly1;
while (current->next != NULL) {
current = current->next;
}
current->next = new;
}
}
return result;
}
int main() {
struct node *poly1 = NULL;
struct node *poly2 = NULL;
struct node *result = NULL;
free(poly1);
free(poly2);
free(result);
return 0;
}