In: Computer Science
Assume that a singly linked list is implemented with a header
node, but no tail node, and that it maintains only a pointer to the
header node. Write a class in C++ that includes methods to
a. return the size of the linked list
b. print the linked list
c. test if a value x is contained in the linked list
d. add a value x if it is not already contained in the linked
list
e. remove a value x if it is contained in the linked list
CODE IN C++ :
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node*next;
Node(int data)
{
this->data=data;
this->next=NULL;
}
};
int size_linkedlist(Node*head) //function to find the size of the
given linked list
{
if(head==NULL)
{
return 0;
}
Node*temp=head;
int size=0;
while(temp->next!=NULL)
{
temp=temp->next;
size++;
}
return size+1;
}
void print(Node* head) //function to print the linked list
{
if(head==NULL)
{
cout<<-1;
}else{
Node*temp=head;
while(temp->next!=NULL)
{
cout<<temp->data<<" " ;
temp=temp->next;
}
cout<<temp->data;
}
}
bool test(Node*head,int x)//function to test if a number is present
in the linked list or not
{
Node*temp=head;
while(temp->next!=NULL)
{
if(temp->data==x)
{
return true;
}
}
return false;
}
void add(Node *head,int x) //function to add a node to the linked
list
{
Node*temp=head;
while(temp->next!=NULL)
{
if(temp->data==x)
{
cout<<"Number is already there";
}else
{
temp=temp->next;
}
}
Node* addnode=new Node(x);
temp->next=addnode;
return;
}
void remove(Node*head,int x) //function to remove a node from a
linked list
{
Node*temp=head;
while(temp->next!=NULL)
{
if(temp->data==x)
{
Node*temp2=head;
while(temp2->next->data!=x)
{
temp2=temp2->next;
}
temp2->next=temp->next;
return;
}else{
temp = temp->next;
}
}
}
int main()
{
Node*head=new Node(1);
Node*second=new Node(2);
Node*third=new Node(3);
Node*fourth=new Node(4);
head->next=second;
second->next=third;
third->next=fourth;
int size=size_linkedlist(head);
cout<<"The size of linked list is :
"<<size<<endl;
print(head);
cout<<endl;
remove(head,3);
print(head);
cout<<endl;
add(head,5);
print(head);
}
OUTPUT SNIPPET: