0% found this document useful (0 votes)
1 views

Circular Linked List

Circular linked list

Uploaded by

ajmatsiddqui7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Circular Linked List

Circular linked list

Uploaded by

ajmatsiddqui7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Circular Linked List

#include<iostream>
#define N 10
using namespace std;

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

class LinkedList
{
node *head;
int n;
public:
LinkedList(); //Constructor
void addatstart(int x); //For adding a node at start
void append(int x); //For adding a node at end
void add(int x,int l); //For adding a node at specified location
void delfromstart(); //For deleting a node from start
void delfromend(); //For deleting a node from end
void del(int l); //For deleting a node from specified location
void display(); //Displaying the LinkedList
};

LinkedList::LinkedList()
{
n=0;
head=NULL;
}

void LinkedList::addatstart(int x)
{
node *r;
r=new node;
r->data=x;
if(n==0)
{
r->next=r;
}
else
{
node *t=head;
for(int i=0;i<(n-1);i++)
{
t=t->next;
}
t->next=r;
r->next=head;
}
head=r;
n++;
}

void LinkedList::append(int x)
{
if(n==0)
{
addatstart(x);
}
else
{
node *r,*t;
r=new node;
r->data=x;
r->next=head;
t=head;
for(int i=0;i<(n-1);i++)
{
t=t->next;
}
t->next=r;
n++;
}
}

void LinkedList::add(int x,int l)


{
if(l<0 || l>n)
{
cout<<"Invalid Location"<<endl;
}
else
{
if(l==0)
{
addatstart(x);
}
else if(l==n && l>0)
{
append(x);
}
else
{
node *r,*t1,*t2;
r=new node;
r->data=x;
t1=head;
for(int i=0;i<(l-1);i++)
{
t1=t1->next;
}
t2=t1->next;
t1->next=r;
r->next=t2;
n++;
}
}
}

void LinkedList::display()
{
if(n==0)
{
cout<<"LinkedList is empty"<<endl;
}
else
{
node *t=head;
for(int i=0;i<n;i++)
{
cout<<t->data<<endl;
t=t->next;
}
}
}

void LinkedList::delfromstart()
{
if(n==0)
{
cout<<"List is empty."<<endl;
}
else
{
node *t=head;
head=head->next;
delete t;
if(n==1)
{
head=NULL;
}
else
{
t=head;
for(int i=0;i<(n-2);i++)
{
t=t->next;
}
t->next=head;
}
n--;
}
}

void LinkedList::delfromend()
{
if(n==0)
{
cout<<"List is empty."<<endl;
}
else if(n==1)
{
delfromstart();
}
else
{
node *t1,*t2;
t1=head;
for(int i=0;i<(n-2);i++)
{
t1=t1->next;
}
t2=t1->next;
t1->next=head;
delete t2;
n--;
}
}

void LinkedList::del(int l)
{
if(l<0 || l>n-1)
{
cout<<"Invalid Location"<<endl;
}
else
{
if(l==0)
{
delfromstart();
}
else if(l==n-1 && l>0)
{
delfromend();
}
else
{
node *t1,*t2;
t1=head;
for(int i=0;i<(l-1);i++)
{
t1=t1->next;
}
t2=t1->next;
t1->next=t2->next;
delete t2;
n--;
}
}
}

int main()
{
LinkedList obj;
obj.addatstart(10);
obj.addatstart(13);
obj.append(21);
obj.addatstart(6);
obj.add(11,2);
obj.append(55);
obj.display();
obj.del(3);
cout<<endl;
obj.display();
obj.delfromstart();
cout<<endl;
obj.display();
obj.delfromend();
cout<<endl;
obj.display();
return(0);
}

You might also like