0% found this document useful (0 votes)
20 views41 pages

Datastructures Uniti

datastructures unitI

Uploaded by

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

Datastructures Uniti

datastructures unitI

Uploaded by

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

DATA STRUCTURES AND ALGORITHMS

UNIT I:
Abstract Data Types (ADTs)- List ADT-array-based implementation-linked list implementation singly linked
lists-circular linked lists-doubly-linked lists-applications of lists-Polynomial Manipulation- All operations-
Insertion-Deletion-Merge-Traversal
UNIT II
Stack ADT-Operations- Applications- Evaluating arithmetic expressions – Conversion of infix to postfix
expression-Queue ADT-Operations-Circular Queue- Priority Queue- de Queue applications of queues.
UNIT III
Tree ADT-tree traversals-Binary Tree ADT-expression trees-applications of trees-binary search tree ADT-
Threaded Binary Trees-AVL Trees- B-Tree- B+ Tree – Heap-Applications of heap.
UNIT IV
Definition- Representation of Graph- Types of graph-Breadth first traversal – Depth first traversal-
Topological sort- Bi-connectivity – Cut vertex- Euler circuits-Applications of graphs.
UNIT V
Searching- Linear search-Binary search-Sorting-Bubble sort-Selection sort-Insertion sort-Shell sort-Radix
sort-Hashing-Hash functions-Separate chaining- Open Addressing-Rehashing Extendible Hashing
Text Books:

1. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C++”, Pearson Education 2014, 4th Edition.
2.ReemaThareja, “Data Structures Using C”, Oxford Universities Press 2014, 2nd Edition

Reference Books:

1.Thomas H.Cormen,ChalesE.Leiserson,RonaldL.Rivest, Clifford Stein, “Introduction to Algorithms”, McGraw


Hill 2009, 3rd Edition.
2. Aho, Hopcroft and Ullman, “Data Structures and Algorithms”, Pearson Education 2003

Web Resources:

1. https://www.programiz.com/dsa
2. https://www.geeksforgeeks.org/learn-data-structures-and-algorithms-dsa-tutorial/
Unit i
Abstract data types (ADT) – list ADT – array-based implementation – linked list implementation
––singly linked lists- circularly linked lists- doubly-linked lists– applications of lists –polynomial
manipulation – all operation (insertion, deletion, merge, traversal)

Data:
A collection of facts, concepts, figures, observations, occurrences or instructions in a
Formalized manner.
Information:
The meaning that is currently assigned to data by means of the conventions applied to
those data (i.e. processed data)
Record:
Collection of related fields.
Data type:
Set of elements that share common set of properties used to solve a program.
Datastructures:
Data structure is the way of organizing, storing, and retrieving data and their relationship
with each other.
Characteristics of data structures:
1. It depicts the logical representation of data in computer memory.
2. It represents the logical relationship between the various data elements.

3. It helps in efficient manipulation of stored data elements.

4. It allows the programs to process the data in an efficient manner.

Operations on data structures:

1. Traversal

2.search

3. Insertion

4.deletion

Data Structures and Algorithms


Classification of data structures

Primary data structures primitive data structures:


Primitive data structures include all the fundamental data structures that can be directly
Manipulated by machine-level instructions. Some of the common primitive data structures include
integer, character, real, boolean etc

Secondary data structures/non primitive data structures:


Non-primitive data structures refer to all those data structures that are derived from one or
more primitive data structures. The objective of creating non-primitive data structures is to form
sets of homogeneous or heterogeneous data elements.

Linear data structures:


Linear data structures are data structures in which, all the data elements are arranged linear
or sequential fashion. Examples of data structures include arrays, stacks, queues, linked lists, etc.

Non linear structures:


In non-linear data structures, there is definite order or sequence in which data elements are
arranged. For instance, a non-linear data structures could arrange data elements in a hierarchical
fashion. Examples of non-linear data structures are trees and graphs.

Static and dynamic data structure:

Static DD:

If a data structures is created using static memory allocation, ie.ds formed when the number of
data items are known in advance, it is known as static data static data structures or fixed size data
structures.
Dynamic ds:
Data Structures and Algorithms
If the data structures is created using dynamic memory allocation i.eds formed when the
number of data items are not known in advance is known as dynamic data structures or variable
size data structures.

Application of data structures:


Data structures are widely applied in the following areas:

 Compiler design operating system


 Statistical analysis is package
 DBMS
 Numerical analysis simulation
 Artificial intelligence
 Graphics

Abstract data types(ADT):

An abstract data type (ADT) is defined as a mathematical model with a collection of operations
defined on that model. Set of integers, together with the operations of union, intersection and set
difference form an example of an ADT. An ADT consists of data together with functions that
operate on that data.
Advantages/benefits of adt:
1. Modularity
2.reuse
3. Code is easier to understand
4. Implementation of ADTS can be changed without requiring changes to the program that uses
the ADTS.

The list ADT:


List is an ordered set of elements.

The general form of the list is a1,a2,……,ana1-

first element of the list


A2-1stelement of the list

N–size of the list

If the element at position i is ai, then its successor is ai+1and its predecessor is ai-1

Data Structures and Algorithms


Various operations performed on list

1. Insert(x, 5)-insert the element x after the position 5.

2. Delete(x)-the element x is deleted

3. Find(x)-returns the position of x.

4. Next (i)-returns the position of its successor element i+1.

5. Previous (i)-returnsthepositionofitspredecessori-1.

6. Print list –contents of the list is displayed.

7. Make empty-makes the list empty.

Implementation of list adt:

1. Array based implementation

2. Linked list based implementation

Array implementation of list:


Array is a collection of specific number of same type of data stored in consecutive memory
locations. Array is a static data structure i.e., the memory should be allocated in advance and the
size is fixed. This will waste the memory space when used space is less than the allocated space.

Insertion and deletion operation are expensive, as it requires more data movements

find and print list operations takes constant time.

The basic operations performed on a list of elements are


a. Creation of list.
b. Insertion of data in the list
c. Deletion of data from the list
d. Display all data’s in the list
Data Structures and Algorithms
e. Searching for a data in the list.

Declaration of array:

#define maxsize 10
int list[maxsize], n ;
create operation:
Create operation is used to create the list with „ n „ number of elements .if “n” exceeds the
array’s max size, then elements cannot be inserted into the list. Otherwise the array elements are
stored in the consecutive array locations (i.e.) List [0], list [1] and so on.
Void create()
{
Int i;
Printf(" enter the number of elements to be added in the list:");

Scanf ("%d",&n);
Printf("enter the array elements:");
for(i=0;i<n;i++)
Scanf("%d", &list[i]);
}

If n=6, the output of creation is as follows:


List[6]

Insert operation:
Insert operation is used to insert an element at particular position in the existing list. Inserting the
element in the last position of an array is easy. But inserting the element at a particular position in
an array is quite difficult since it involves all the subsequent elements to be shifted one position to
the right.
Data Structures and Algorithms
Insert an element in the array:
Void insert()
{
Inti, data, pos;
Printf("enter the data to be inserted:\t");

scanf("%d", &data);
Printf("enter the position at which element to be inserted:\t");
scanf("%d",&pos);
If(pos==n)
Printf (“array overflow”);
for(i=n-1;i>=pos-1;i--)
List[i+1]=list[i];
list[pos-1] = data;
n=n+1;
Display();}
Consider an array with5elements[maxelements=10]

10 20 30 40 50

if data 15 is to be inserted in the 2nd position than 50 has to be moved to next index position, 40
has to be moved to50 position,30 has to be moved to40 position and 20 has to be moved to 30
position.

10 20 30 40 50

10 20 30 40 50

Data Structures and Algorithms


After this four data movement, 15 is inserted in the 2ndposition of the array.

10 15 20 30 40 50

Deletion operation:
Deletion is the process of removing an element from the array at any position.
Deleting an element from the end is easy. If an element is to be deleted from any particular
position , it requires all subsequent element from that position is shifted one position towards left.
Routine to delete an element in the array:
Void delete()
{
int i, pos ;
Printf("Enter the position of the data to be deleted:\t");

scanf("%d",&pos);
Printf("Enter the data deleted is:\t%d", list[pos-1]);
for(i=pos-1;i<n-1;i++)
List[i]=list[i+1] ;
n=n-1;
Display();
}
Consider an array with 5 elements [max elements=10 ]

10 20 30 40 50

Data Structures and Algorithms


if data 20 is to be deleted from the array, then 30 has to be moved to data 20 position, 40 has to
be moved to data 30 position and 50 has to be moved to data 40 position.

10 20 30 40 50

After this3data movements, data20is deleted from the2nd position of the array.

10 30 40 50

Display operation/ traversing a list


Traversal is the process of visiting the elements in a array.
Display ( ) operation is used to display all the elements stored in the list. The elements are stored
from the index 0 to n - 1. Using a for loop, the elements in the list are viewed
Routine to traverse/display elements of the array:
Void display()
{
int i;
Printf("\n**********elements in the array**********\n");
for(i=0;i<n;i++)
Printf("%d\t",list[i]);
}

Search operation:
Search( ) operation is used to determine whether a particular element is present in the list or not.
Input the search element to be checked in the list.
Routine to search an element in the array:
Void search()
{
Intsearch,i,count= 0;
Data Structures and Algorithms
Printf("\nentertheelementtobesearched:\t");
scanf("%d",&search);
For(i=0;i<n;i++)
{
If(search==list[i])
count++;
}

If(count==0)
Printf("\nelementnotpresentinthelist"); else
Printf("\nelementpresentinthelist");
}

Program for array implementation of list


#include<stdio.h>
#include<conio.h>#
definemaxsize10
int list[maxsize],n;
void create();
void insert();
void delete();
void display();
void search();
void main()
{
int choice;
clrscr();do
{
Printf("\narray implementation of list\n");
printf("\t1.create\n");
Printf("\t2.insert\n");
printf("\t3.delete\n");
printf("\t4.display\n");
printf("\t5.search\n");
printf("\t6.exit\n");
printf("\nenteryourchoice:\t");
scanf("%d", &choice);
switch(choice)
{

Data Structures and Algorithms


Case1:create();
Break;
case2:insert();
Break;
case3:delete();
Break;
case4:display();
Break;
case5:search();
Break;
case6:exit(1);
Default:printf("\nenteroptionbetween1-6\n"); break;
}
}while(choice<7);
}
Void create()
{
int i;
Printf("Enter the number of elements to be added in the list:\t");
scanf("%d",&n);
Printf("Enter the array elements:\t");
for(i=0;i<n;i++)
Scanf("%d",&list[i]);
display();
}
Void insert()
{
inti,data,pos;
Printf("Enter the data to be inserted:\t");
scanf("%d",&data);
Printf("Enter the position at which element to be inserted:\t");
scanf("%d",&pos);
For(i=n-1;i>=pos-1;i--) list[i+1] =
list[i];
List[pos-1]=data;
n+=1;
Display();
}
Void delete()
{
Int i,pos;
Printf("Ente rthe position of the data to be deleted:\t");
scanf("%d",&pos);
Printf("The data deleted is:\t%d", list[pos-1]);
for(i=pos-1;i<n-1;i++)

Data Structures and Algorithms


List[i]=list[i+1];
n=n-1;
display();
}

Void display()
{
int i;
Printf("\n**********elements in the array**********\n");
for(i=0;i<n;i++)
Printf("%d\t",list[i]);
}

Void search()
{
Int search,i, count= 0;
Printf("Enter the element to be searched:\t");
scanf("%d",&search);
For(i=0;i<n;i++)
{
If(search==list[i])
{
Count++;
}
}
If(count==0)
Printf("Element not present in the list");
else
Printf("Element present in the list");
}
Output

Array implementation of list

1.create
2. Insert
3.delete
4.display
5.search
6.exit
Enter your choice: 1

Enterthenumberofelementstobeaddedinthelist:5 enter

the array elements: 12345


Data Structures and Algorithms
**********elements in the array**********

1 2 3 4 5

Array implementation of list

1.create
2. insert
3.delete
4.display
5.search
6.exit

Enter your choice: 2

Enter the data tobeinserted:3

Enter the position at which element to be inserted: 1

**********elements in the array**********

3 1 2 3 4 5

Array implementation of list

1.create
2. insert
3.delete
4.display
5.search 6.exit

Enter your choice: 3

Enter the position of the data to be deleted: 4

the data deleted is: 3

**********elements in the array**********

3 1 2 4 5

Array implementation of list

Data Structures and Algorithms


1.create
2.insert
3.delete
4.display
5.search 6.exit

Enter your choice: 5

Enter the element to be searched: 1

element present in the list

Array implementation of list


1. Create
2. Insert
3.delete
4.display
5.search
6.exit
Enter yourchoice:6

Advantage of array implementation:


1. The elements are faster to access using random access
2.searching an element is easier

Limitation of array implementation


An array stores its nodes inconsecutive memory locations.
The number of elements in the array is fixed and it is not possible to change the number of
elements.
Insertion and deletion operation in array are expensive. Since insertion is performed by
pushing the entire array, one position down and deletion is performed by shifting the
entire array one position up.
Applications of arrays:
Arrays are particularly used in programs that requies to ring large collection of similar type data
elements.

Data Structures and Algorithms


Differences between array based and linked based implementation

Array Linked list


Definition Array is a collection of elements Linked list is an ordered
having same data type with common collection of elements which are
Name connected by
Links/pointers
Access Elements can be accessed Sequential access
using index/subscript,
random access
Memory structure Elements are stored in contiguous Elements are stored at available
memory locations memory space

Insertion &deletion Insertion and deletion takes more Insertion and deletion are fast and
time in array easy

Memory allocation Memory is allocated at compile time Memory is allocated at run time
i.e static memory allocation i.e dynamic memory allocation

Types 1D,2D,multi-dimensional Single, Double and circular linked


list.
Dependency Each elements is independent Each node is dependent on each
other as address part contains
address of next node in the list

Data Structures and Algorithms


LIST ADT:
Listisbasicallythecollectionofelementsarrangedinasequentialmanner.in memory we
can store the list in two ways: one way is we can store the elements in sequential memory
locations. That means we can store the list in arrays. The other way is we can use pointers
or links to associate elements sequentially. This is known as linked list.

Linked lists

Thelinkedlistisverydifferenttypeofcollectionfromanarray.usingsuchlists, we can
store collections of information limited only by the total amount of memory that the os will
allow us to use. Further more, there is no need to specify our needs in advance. The linked
list is very flexible dynamic data structure: items may be added to it or deleted from it at
will. A programmer need not worry about how many items a program will have to
accommodate in advance. This allows us to write robust programs, which require much
less maintenance.

The linked allocation has the following draw backs:

1. No direct access to a particular element.


2. Additional memory required for pointers.

Linked list are of 3 types:

1. Singly linked list


2. Doubly linked list
3. Circularly linked list

Singly linked list

A singly linked list, or simply a linked list, is a linear collection of data items. The
linear order is given by means of pointers. These types of lists are often referred to as
linear linked list.
* Each item in the list is called a node.
* Each node of the list has two fields:
1. Information-contains the item beings to red in the list.
2. Next address-contains the address of the next item in the list.
*the last node in the list contains null pointer to indicate that it is the end of
the list. Conceptual view of singly linked list
Operations on singly linked list:

insertion of a node
deletions of a node
traversing the list

Structure of a node:

method -1:

struct node
{ Data link
int data;
struct node *link;
};

Method-2:

Class node
{
Public:
int data;
node*link;
};

Insertions: to place an elements in the list there are 3cases :


1. At the beginning
2. End of the list
3. At a given position

Case1:insert at the beginning

temp

Head is the pointer variable which contains address of the first node and temp contains
address of new node to be inserted then sample code is

temp->link=head;
head=temp;
Afterinsertion:

code for insert front:-

Template<classt>
Void list<t>::insert_front()
{
struct node <t>*t,*temp;
cout<<"enter data in to node:";
cin>>item;
temp=create_node(item);
if(head==null)
Head=temp;
Else
{
temp->link=head;
Head=temp;
}
}

Case2:inserting end of the list

Temp

Head is the pointer variable which contains address of the first node and temp contains
address of new node to be inserted then sample code is

t=head;
while(t->link!=NULL)
{
t=t->link;
}
t->link=temp;
After insertion the linked list is

code for insert end:-

Template<classt>
Void list<t>::insert_end()
{
structnode<t>*t,*temp;
int n;
Cout<<"enter data in to node:";
cin>>n;
Temp=create_node(n);
if(head==null)
Head=temp;
Else
{
t=head;
while(t->link!=null)
T=t->link;
t->link=temp;
}
}

Case3: insert at a position

Insert node at position 3


Head is the pointer variable which contains address of the first node and temp contains
address of new node to be inserted then sample code is

c=1;
while(c<pos)
{
prev=cur;
cur=cur->link;
c++;
}
prev->link=temp;
temp->link=cur;
Code for inserting a nod eat a given position:-

Template<classt>
Voidlist<t>::insert_at_pos(intpos)
{
structnode<t>*cur,*prev,*temp;
int c=1;
Cout<<"enter data in to node:"; cin>>item
temp=create_node(item);
if (head==null)
Head=temp;
Else
{
Prev=cur=head;
if(pos==1)
{
temp->link=head;
head=temp;
}
Else
{
while(c<pos)
{
c++;
Prev=cur;
cur=cur->link;
}
Prev->link=temp;
temp->link=cur;
}
}
}

Deletions:
Removing an element from the list, without destroying the integrity of the list itself.
To place an element from the list there are 3cases:
1. Delete a nod eat beginning of the list.
2. Delete a node at end of the list.
3. Delete a node at a given position.
c

ase1:delete a node at beginning of the list


head

Head is the pointer variable which contains address of the first node

Sample code is
T=head;
head=head->link;
cout<<"node"<<t->data<<"deletionissucess"; delete(t);

head

Case2.delete a node at end of the list

head

To delete a node, find the node using following code

structnode<T>*cur,*prev;
cur=prev=head;
while(cur->link!=NULL)
{prev=cur;cur=cur-
>link;
}
prev->link=NULL;
cout<<"node"<<cur->data<<"Deletion is sucess";
free(cur);

head
Code for deleting an node at end of the list
Template<class t>
Void list<t>::delete_end()
{
struct node<t>*cur,*prev;
cur=prev=head;
if(head==null)
cout<<"listis empty\n";
Else
{
cur=prev=head;
if(head->link==null)
{
cout<<"node"<<cur->data<<"deletion is sucess"; free(cur);
Head=null;
}

else
{
while(cur->link!=null)
{
prev=cur;
cur=cur->link;
}
Prev->link=null;
cout<<"node"<<cur->data<<"deletionissucess";
free(cur);
}
}
}

Case3.delete a node at a given position

head

Delete node at position 3


Head is the pointer variable which contains address of the first node. Node to be deleted is
node Containing value 30. Finding node at position3

c=1;
while(c<pos)
{
c++;
prev=cu r;
cur=cur->link;
}
prev cur

10 20 30 40 NULL

Cur is the node to be deleted.before deleting up date links code to update links
Prev->link=cur->link;

cout<<cur->data<<"is deleted successfully";


delete cur;

prev

10 20 30 40 NULL

Traversing the list: Assuming we are given the pointer to the head of the list, how do we
get the end of the list.

Template <class t>


void list<t>::display()
{
Struct node<t>*t;

If(head==null)
{
cout<<"listis empty\n";
}
Else
{
t=head;
While(t!=nul l)
{
cout<<t->data<<"->";
t=t->link;
}
}
}
Doubly linked list
A singly linked list has the disadvantage that we can only traverse it in one direction.
Many applications require searching backwards and forwards through sections of a list. A
useful refinement that can be made to the singly linked list is to create a doubly linked list.
The distinction made between the two list types is that while singly linked list have pointers
going in one direction, doubly linked list have pointer both to the next and to the previous
element in the list. The main advantage of a doubly linked list is that, they permit traversing
or searching of the list in both directions.

In this linked is teach node contains three fields.


a) One to store data
b) Remaining are self referential pointers which points to previous and next
nodes in the list

Prev Data Next

Implementation of node using structure

method -1:

struct node
{
int data;
struct node *prev;
structnode * next;
};

Implementation of node using class

method -2:

Class node
{
Public:
int data;
node *prev;
node* next;
};

NUL
NULL 10 20 30 L

operations on doubly linked list:


insertion of a node
deletions of a node
traversing the list
Doubly linked list ADT:

Template<classt>

class dlist
{
int data;
Struct dnode<t>*head;
Public:
dlist()
{
head=null;
}
Void display();
Struct dnode<t>*create_dnode(intn);
void insert_end();
Void insert_front();
void delete_end();
void delete_front();
voiddnode_count();

void insert_at_pos(int pos);


voiddelete_at_pos(intpos);
};

Insertions: To place an elements in the list there are 3 cases


1. At the beginning
2. End of the list
3. At a given position

Case1:insert at the beginning

head is the pointer variable which contains address of the first node and temp contains
address of new node to be inserted then sample code is

temp->next=head;
head->prev=temp;
head=temp;
head

NUL
40 10 20 30 L
Codeforinsert front:-

Template<classt>
Void dll<t>::insert_front()
{
Struct dnode <t>*t,*temp;
cout<<"enter data in to node:";
cin>>data;
temp=create_dnode(data);
if(head==null)
Head=temp
else
{
tempt>next=head;
head->prev=temp;
Head=temp;

}
}
code to insert a node at end:-

Template<classt>
Void dll<t>::insert_end()
{
Struct dnode<t>*t,*temp; int n;
cout<<"enter data in to dnode:";
cin>>n;
Temp=create_dnode(n);
if(head==null)
Head=temp;
Else
{
t=head;
while(t->next!=null)
T=t->next;
t->next=temp;
Temp->prev=t;
}
}
Code to insert a node at a position

Template<classt>
Void dlist<t>::insert_at_pos(int pos)
{
struct dnode<t>*cr,*pr,*temp;
int count=1;
Cout<<"enter data in to dnode:";
cin>>data;
temp=create_dnode(data);
display();
If(head==null)
{ //whenlistis empty
Head=temp;
}
Else
{
pr=cr=head;
if(pos==1)
{ //insertingatpos=1
temp->next=head;
head=temp;
}
else
{
While(count<pos)
{
count++;
Pr=cr;
cr=cr->next;
}
Pr->next=temp;
temp->prev=pr;
temp->next=cr;
cr->prev=temp;
}
}
}

Deletions: Removing an element from the list, without destroying the integrity of the list
itself.

To place an element from the list there are 3 cases:


1. Delete a node at beginning of the list
2. Delete a node at end of the list
3. Delete a node at a given position
case1:delete a node at beginning of the list

head

NUL NUL
L 10 20 30 L

head is the pointer variable which contains address of the first node

sample code is

t=head;
head=head->next;
head->prev=NULL;
cout<<"dnode"<<t->data<<"Deletion is sucess";
delete(t);

head

NUL
NULL 10 NULL 20 30 L

code for deleting a node at front

Template<classt>
Void dlist<t>::delete_front()
{
struct dnode<t>*t;
if(head==null)
Cout<<"listis empty\n";
else
{
t=head;
head=head->next;
head->prev=null;
cout<<"dnode"<<t->data<<"deletion is sucess";
delete(t);
}
}
Case2. Delete a node at end of thel ist
To deleted the last node find the last node. Find the node using following code

Struct dnode<T>*pr,*cr;

pr=cr=head;
while(cr->next!=NULL)
{
pr=cr;
cr=cr->next;
}
pr->next=NULL;
cout<<"dnode"<<cr->data<<"Deletion is sucess";
delete(cr);

head

NULL 10 20 NULL 30 NULL

Pr cr

Code for deleting a node at end of the list

Template<classt>
Void dlist<t>::delete_end()
{
struct dnode<t>*pr,*cr;
pr=cr=head;
if(head==null)
cout<<"listis empty\n";
Else
{
cr=pr=head;
if(head->next==null)
{
cout<<"dnode"<<cr->data<<"deletion is success";
delete(cr);
head=null;
}
else
{
while(cr->next!=null)
{
pr=cr;
cr=cr->next;
}
pr->next=null;
Cout<<"dnode"<<cr->data<<"deletionissucess"; delete(cr);
}
}
case3.delete a node at a given position
head

NULL 10 30 20 NULL

Delete node at position 2


Head is the pointer variable which contains address of the first node.node to be deleted is
node Containing value 30. Finding node at position 2.

While(count<pos)
{
pr=cr;
cr=cr->next;
count++;
}
Pr->next=cr->next;
cr->next->prev=pr;

Head

NUL
L
NULL 10 30 20

cr
pr

circularly linked list


A circularly linked list, or simply circular list, is a linked list in which the last node is
always points to the first node. This type of list can be build just by replacing the null
pointerattheendofthelistwithapointerwhichpointstothefirstnode.thereisnofirstor last node in
the circular list.

Advantages:
Any node can be traversed starting from any other node in the list.
There is no need of null pointer to signal the end of the list and hence, all
pointers contain valid addresses.
In contrast to singly linked list, deletion operation in circular list is simplified as the
search for the previous node of an element to be deleted can be started from that
item itself.

head
Advantagesofcircularlinkedlist

itallows to traversethelist startingat anypoint.


itallowsquickaccesstothefirstandlast records.
circularlydoublylinkedlist allows to traversethelistin eitherdirection.

Applicationsoflist:

1. Polynomialadt

2. Radixsort

3.multilist

Polynomialmanipulation
Polynomialmanipulationssuchasaddition,subtraction&differentiationetc..canbe performed
using linked list
Declarationforlinkedlistimplementationofpolynomialadt
structpoly
{
int coeff;
intpower;
structpoly*next;
}*list1,*list2,*list3;

Creationofthepolynomial
Polycreate(poly*head1,poly*newnode1)
{
Poly *ptr;
if(head1==null)
{
head1=newnode1;
return (head1);
}
Els
e
{ Ptr=head1;
While(ptr->next!=null)
ptr=ptr->next;
Ptr->next=newnode1;

}
Return(head1);
}
Additionoftwopolynomials
Void add()
{
Poly*ptr1,*ptr2,*newnode;
ptr1= list1;
Ptr2 =list2;
While(ptr1 !=null&&ptr2!=null)
{

Newnode=(structpoly*)malloc(sizeof(structpoly)); if(
ptr1 -> power = = ptr2 -> power )
{
Newnode->coeff =ptr1->coeff+ptr2->coeff;
Newnode->power=ptr1->power;
newnode -> next = null;
List3=create(list3,newnode); ptr1
= ptr1 -> next;
Ptr2=ptr2 ->next;
}
Elseif(ptr1->power>ptr2->power )
{
newnode -> coeff = ptr1 -> coeff;
newnode->power=ptr1->power; newnode
-> next = null;
List3=create(list3,newnode); ptr1
= ptr1 -> next;
}
Else
{
Newnode -> coeff = ptr2 -> coeff;
newnode->power=ptr2->power; newnode
-> next = null;
List3=create(list3,newnode);
Ptr2=ptr2 ->next;
}}}

Subtractionoftwopolynomial
{
Void sub() poly*ptr1,*ptr2,*newnode;
ptr1 = list1;
Ptr2 =list2;
While(ptr1 !=null&&ptr2!= null)
{
Newnode=(structpoly*)malloc(sizeof(structpoly));
if(ptr1->power==ptr2->power)
{
Newnode->coeff=(ptr1-coeff)-(ptr2->coeff);
newnode->power=ptr1->power;
Newnode->next=null;
list3=create(list3,newnode);
ptr1=ptr1->next;

Ptr2=ptr2->next;
}
Else
{
If(ptr1-power>ptr2-power)
{
newnode->coeff=ptr1->coeff;
newnode->power=ptr1->power;
newnode->next=null;
list3=create(list3,newnode);
ptr1=ptr1->next;
}
Else
{
Newnode->coeff=-(ptr2->coeff);
newnode->power=ptr2->power;
newnode->next=null;
list3=create(list3,newnode);
ptr2=ptr2->next;
}
}
}

Polynomialdifferentiation:

Void diff()

Poly*ptr1,*newnode;
ptr1 = list1;
While(ptr1!=null)
{
Newnode=(structpoly*)malloc(sizeof(struct poly));

Newnode->coeff=(ptr1-coeff)*(ptr1->power);
newnode->power=ptr1->power-1;
Newnode->next=null;
list3=create(list3,newnode);
ptr1=ptr1->next;
}
}
Polynomialmultiplication

Void mul()
{
Poly*ptr1,*ptr2,*newnode; ptr1=
list1;
Ptr2 =list2;
While(ptr1 !=null&&ptr2!=null)
{
Newnode=(structpoly*)malloc(sizeof(structpoly)); if(
ptr1 -> power = = ptr2 -> power )
{
Newnode -> coeff = ptr1 -> coeff * ptr2 -> coeff;
newnode->power=ptr1->power+ptr2->power;; newnode
-> next = null;
List3=create(list3,newnode); ptr1
= ptr1 -> next;
Ptr2=ptr2 ->next;
}}
}
Advantages of Circular linked List

It allows to traverse the list starting at any point.


It allows quick access to the first and last records.
Circularly doubly linked list allows to traverse the list in either direction.

Applications of List:

1. Polynomial ADT

2.Radix sort

3.Multilist

Polynomial Manipulation
Polynomial manipulations such as addition, subtraction & differentiation etc.. can be
performed using linked list
Declaration for Linked list implementation of Polynomial ADT
struct poly
{
int coeff;
int power;
struct poly *next;
}*list1,*list2,*list3;

Creation of the Polynomial


poly create(poly*head1,poly*newnode1)
{
poly *ptr;
if(head1==NULL)
{
head1=newnode1;
return (head1);
}
else
{
ptr=head1;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=newnode1;
}
return(head1);
}
Addition of two polynomials
void add()
{
poly *ptr1, *ptr2, *newnode ;
ptr1= list1;
ptr2 = list2;
while( ptr1 != NULL && ptr2 != NULL )
{

newnode = (struct poly*)malloc( sizeof ( struct poly ));


if( ptr1 -> power = = ptr2 -> power )
{
newnode -> coeff = ptr1 -> coeff + ptr2 -> coeff;
newnode -> power = ptr1 -> power ;
newnode -> next = NULL;
list3 = create( list3, newnode );
ptr1 = ptr1 -> next;
ptr2 = ptr2 -> next;
}
else if(ptr1 -> power > ptr2 -> power )
{
newnode -> coeff = ptr1 -> coeff;
newnode -> power = ptr1 -> power;
newnode -> next = NULL;
list3 = create( list3, newnode );
ptr1 = ptr1 -> next;
}
else
{
newnode -> coeff = ptr2 -> coeff;
newnode -> power = ptr2 -> power;
newnode -> next = NULL;
list3 = create( list3, newnode );
ptr2 = ptr2 -> next;
}}}

Subtraction of two polynomial


{
void sub() poly *ptr1, *ptr2, *newnode;
ptr1 = list1;
ptr2 = list2;
while( ptr1 != NULL && ptr2 != NULL )
{
newnode = (struct poly*)malloc( sizeof (struct poly)) ;
if(ptr1->power==ptr2->power)
{
newnode->coeff=(ptr1-coeff)-(ptr2->coeff);
newnode->power=ptr1->power;
newnode->next=NULL;
list3=create(list3,newnode);
ptr1=ptr1->next;

ptr2=ptr2->next;
}
else
{
if(ptr1-power>ptr2-power)
{
newnode->coeff=ptr1->coeff;
newnode->power=ptr1->power;
newnode->next=NULL;
list3=create(list3,newnode);
ptr1=ptr1->next;
}
else
{
newnode->coeff=-(ptr2->coeff);
newnode->power=ptr2->power;
newnode->next=NULL;
list3=create(list3,newnode);
ptr2=ptr2->next;
}
}
}

Polynomial Differentiation:

void diff()

poly *ptr1, *newnode;


ptr1 = list1;
while( ptr1 != NULL)
{
newnode = (struct poly*)malloc( sizeof (struct poly));

newnode->coeff=(ptr1-coeff)*(ptr1->power);
newnode->power=ptr1->power-1;
newnode->next=NULL;
list3=create(list3,newnode);
ptr1=ptr1->next;
}
}
Polynomial Multiplication

void mul()
{
poly *ptr1, *ptr2, *newnode ;
ptr1= list1;
ptr2 = list2;
while( ptr1 != NULL && ptr2 != NULL )
{
newnode = (struct poly*)malloc( sizeof ( struct poly ));
if( ptr1 -> power = = ptr2 -> power )
{
newnode -> coeff = ptr1 -> coeff * ptr2 -> coeff;
newnode -> power = ptr1 -> power+ptr2->power; ;
newnode -> next = NULL;
list3 = create( list3, newnode );
ptr1 = ptr1 -> next;
ptr2 = ptr2 -> next;
}}
}

You might also like