Write a program to create and fill a circular singly linked list with computer s
ID: 3746042 • Letter: W
Question
Write a program to create and fill a circular singly linked list with computer science (you can ask the user to enter a sentence e.g I Love C++))
Computer science
- Round 1: start from head C and select every other letter remove it and put it in a removal list (add at the end function).
- Count the number of rounds needed to empty the circular list into removal single list and Print the contents of the removal list.
Advanced option (optional)
Try your program with different sentences and record the time
For example
Computer science 10 sec
I love programming in c++ 12 sec
Explanation / Answer
#include<iostream>
#include<cstdlib>
using namespace std;
class node
{
public:
char c;
node *next;//single link
//constructor.
node(char cc)
{
c =cc;
next=NULL;
}
};
//class for circular single linked list
class CircularSingle
{
public:
node *head,*tail;//main list
node *removal_list;//removal list
//constructor.
CircularSingle()
{
head=NULL;
removal_list=NULL;
}
//method to insert at front
node* insert(char c,node *head)
{
node *n = new node(c);
//cout<<c<<endl;
if(head==NULL){
head=n;
head->next=head;//circular link
tail = n;
}
else
{
n->next = head;
tail->next = n;
head=n;
}
// cout<<head->c<<endl;
return head;
}
//method to delete
void DeleteAll()//removes all contents start from head...and insert it to removal list
{
if(head!=NULL)
{
node *temp =head->next;
removal_list=insert(head->c,removal_list);
while(temp!=head)
{
//inserting to removal list
removal_list=insert(temp->c,removal_list);
temp=temp->next;
}
}
}
//method to display main list
void Display_List()
{
node *temp=head;
cout<<"List contents:";
// cout<<temp->c<<endl;
while(temp!=tail)
{
cout<<temp->c;
temp=temp->next;
}
cout<<temp->c<<endl;
cout<<endl;
}
void Display_removallist()
{
node *temp=removal_list;
cout<<" Removal List contents:";
while(temp->next!=removal_list)
{
cout<<temp->c;
temp=temp->next;
}
cout<<temp->c<<endl;
cout<<endl;
}
};
//testing method
int main()
{
string s;
cout<<"Enter line:";
//readingline
getline(cin,s);
cout<<s<<endl;
int i=0;
//creating circular linked list object
CircularSingle *c= new CircularSingle();
while(s[i]!='')
{
c->head=c->insert(s[i],c->head);//inserting to list
i++;
}
//displaying contents
c->Display_List();
//deleting from list and inserting to removal list
c->DeleteAll();
//displaying removal list contents
c->Display_removallist();
return 0;
}
output:
Enter line:i love c++
i love c++
List contents:++c evol i
Removal List contents:i love c++
Process exited normally.
Press any key to continue . . .
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.