Saturday, 26 November 2016

Circular Linked list


Header file

#ifndef _CIRCULARLINKEDLIST_
#define _CIRCULARLINKEDLIST_
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
class circularLinkedlist
{
private:
Node *last;
public:
circularLinkedlist();
circularLinkedlist(const circularLinkedlist &);
void insertfirst(int);
void deletefirst();
void append(int);
void deletelast();
bool isEmpty();
void print();
void makeEmpty();
~circularLinkedlist();
};
#endif


Cpp File

#include "CircularLinkedList.h"
circularLinkedlist::circularLinkedlist()
{
last=NULL;
}
void circularLinkedlist::insertfirst(int val)
{
Node *temp=new Node;
temp->data=val;
if (isEmpty())
{
last=temp;
temp->next=last;
}else
{
temp->next=last->next;
last->next=temp;

}

}
void circularLinkedlist::print()
{
if(isEmpty())
{
cout<<"No any value in linkedlist "<<endl;
}else
{
Node *ptr=last->next;
do
{
cout <<ptr->data<<endl;
ptr=ptr->next;
}while (ptr!=last->next);
}
}
bool circularLinkedlist::isEmpty()
{
return last==NULL;
}
void circularLinkedlist::deletefirst()
{
if (isEmpty())
{
cout <<"Their is no any node to delete "<<endl;
}else
{
Node *ptr=last->next;
last->next=ptr->next;
if (ptr==last)
{
last=NULL;
}
delete ptr;
}
}
void circularLinkedlist::append(int val)
{
if (isEmpty())
{
insertfirst(val);
}else
{
Node *temp=new Node;
temp->data=val;
temp->next=last->next;
last->next=temp;
last=last->next;
}
}
void circularLinkedlist::deletelast()
{
Node *prev=last->next,*curr=last->next;
if (isEmpty())
{
cout <<"Linkedlist is empty "<<endl;
}else if (curr==last)
{
deletefirst();

}else
{
do
{
prev=curr;
curr=curr->next;
}while (curr!=last);
prev->next=last->next;
last=prev;
delete curr;
}
}
circularLinkedlist::circularLinkedlist(const circularLinkedlist & c)
{
if (c.last==NULL)
{
last=NULL;
}else
{
Node *ptr=c.last->next;
do
{
append(ptr->data);
ptr=ptr->next;
}while (ptr!=last);
}
}
void circularLinkedlist::makeEmpty()
{
if (!isEmpty())
{
Node *ptr=last->next,*del=last->next;
do
{
del=ptr;
ptr=ptr->next;
delete del;
}while (ptr!=last);
ptr=last=NULL;
}
}
circularLinkedlist::~circularLinkedlist()
{
makeEmpty();
}

Main
#include "CircularLinkedList.h"
int main ()
{
circularLinkedlist c;
c.insertfirst(89);
    c.insertfirst(75);
c.insertfirst(100);
c.print();
cout <<"After first deletion "<<endl<<endl;
c.deletefirst();
c.print();
cout <<"Append "<<endl<<endl;
c.append(56);
c.print();
cout <<"after last delition "<<endl<<endl;
c.deletelast();
c.deletelast();
c.print();
cout <<"After calling make empty "<<endl;
c.makeEmpty();
c.print();
return 0;
}

No comments: