Instructions: This chapter defined and identified various operations on a circul
ID: 3595701 • Letter: I
Question
Instructions:
This chapter defined and identified various operations on a circular linked list.
1. Write the definitions of the class circularLinkedListand its member functions. (You may assume that the elements of the circular linked list are in ascending order.)
2. Write a program to test various operations of the class defined in the step above.
Then it will be tested for two input/outputs
Test #1:
Input:
Output:
List 1: 11 22 33 44 55 66 77 88
Length List 1: 8
44 found in the list
After deleting the node, List 1: 11 22 33 44 55 66 88
Test #2:
Input:
Output:
List 1: 123 321 456 654 789 987
Length List 1: 6
1234 not in the list
The item to be deleted is not in the list.
Thanks
Explanation / Answer
#include <iostream>
#include <Windows.h>
using namespace std;
struct node
{
int data;
node * next;
};
class LinkedList
{
public:
LinkedList();
void addition(int A);
bool empty();
void Delete(int x);
void Display();
private:
node * first;
};
LinkedList::LinkedList()
{
first=NULL;
}
void LinkedList::addition(int A)
{
if (first==NULL)
{
first=new node;
first->data=A;
first->next=first;
}
else if (first->next==first)
{
node *current=first->next;
current=new node;
current->data=A;
current->next=first;
first->next=current;
}
else
{
node *current=first->next;
node *prev=NULL;
while (current!=first)
{
prev=current;
current=current->next;
}
current=new node;
current->data=A;
current->next=first;
prev->next=current;
}
}
bool LinkedList::empty()
{
if (first==NULL)
return true;
else return false;
}
void LinkedList::Delete(int A)
{
node *current=first->next;
node *prev=NULL;
bool flag=true;
if (first->data==A)
{
first=first->next;
delete first;
flag=false;
}
else
{
while (flag && current!=first)
{
if (current->data==A)
{
prev->next=current->next;
delete current;
flag=false;
}
prev=current;
current=current->next;
}
if (flag==true)
cout<<"Data not found ";
}
}
void LinkedList::Display()
{
cout<<first->data<<endl;
node *current=first->next;
while (current!=first)
{
cout<<current->data<<endl;
current=current->next;
}
}
int main()
{
int input=0;
int A;
LinkedList One;
while (1)
{
if (input==0)
{
cout<<"1. addition 2. Delete 3. Display ";
cout<<"Enter your choice ";
cin>>input;
}
else if (input==1)
{
cout<<"Enter the data ";
cin>>A;
One.addition(A);
cout<<"Press 0 to go back to main menu ";
cin>>input;
}
else if (input==2)
{
if (One.empty())
cout<<"The list is empty ";
else
{
cout<<"Enter the data to be deleted ";
cin>>A;
One.Delete(A);
}
cout<<"Press 0 to go back to main menu ";
cin>>input;
}
else if (input==3)
{
if (One.empty())
cout<<"The list is empty ";
else
One.Display();
cout<<"Press 0 to go back to main menu ";
cin>>input;
}
}
}