class List
{
  public:
  int item;
  int pos=0;
  List* nextNode;
};
void Insert_Element(List** head, char data)
{
  List* node = new List();
  node->item = data;
  node->nextNode = (*head);Â
  (*head) = node;Â
}
 void PrinList(List *node){
 List *temp = node;
 while(temp !=NULL){
 cout<<temp->item<<" ";
 node->pos ++;
 temp = temp->nextNode;
}
cout<<"\n";
 }
int Length(List *node){
return node->pos;
}
bool is_Empty(List *node){
if(node->pos==0){
return true;
}
else {
return false;
}
}
void Copy_List(List*node, List *list){
List * temp = node;
while(temp !=NULL){
int data = temp->item;
Insert_Element(&list, data);
temp = temp->nextNode;
}
cout<<"The copied list is:\n";
PrinList(list);
}
note:
Create constructor(default,parameterized and copy) and a manu of test the functions.
#include<iostream>
using namespace std;
class List
{
 public:
 int item;
 int pos=0;
 List* nextNode;
 //Default Constructor
 List(){
 pos = 0 ;
 }
//parameterized Constructor
List(int data){
item = data;
nextNode = NULL;
}
//Copy Constructor
List(const List &node){
item = node.item;
}
};
void Insert_Element(List** head, char data)
{
 List* node = new List();
 node->item = data;
 node->nextNode = (*head);Â
 (*head) = node;Â
}
 void PrinList(List *node){
 List *temp = node;
 while(temp !=NULL){
 cout<<temp->item<<" ";
 node->pos ++;
 temp = temp->nextNode;
}
cout<<"\n";
 }
int Length(List *node){
return node->pos;
}
bool is_Empty(List *node){
if(node->pos==0){
return true;
}
else {
return false;
}
}
void Copy_List(List*node, List *list){
List * temp = node;
while(temp !=NULL){
int data = temp->item;
Insert_Element(&list, data);
temp = temp->nextNode;
}
cout<<"The copied list is:\n";
PrinList(list);
}
int main(){
List *node = NULL;
Insert_Element(&node, 9);
Insert_Element(&node, 6);
Insert_Element(&node, 8);
int choice;
do{
cout<<"Select an option:\n";
cout<<"1. Add an element to the linked list.\n2. Get the total number of elements in the linked list.\n3. Check if the linked list is empty.\n";
cout<<"4. Copy the linked list to another list\n. 5. Display the linked list.\n 0 to exit the program\n";
cin>>choice;
if(choice==1){
cout<<"Enter the item\n";
int item;
cin>>item;
Insert_Element(&node, item);
}
else if(choice==2){
cout<<"The total element in the linked list is: "<<Length(node)<<endl;
}
else if(choice == 3){
if(is_Empty(node)==0){
cout<<"The linked list is not empty\n";
}
else{
cout<<"The linked list is empty\n";
}
}
else if(choice== 4){
List *list = NULL;
Copy_List(node,list);
}
else if(choice==5){
PrinList(node);
}
}while(choice!=0);
cout<<"Terminated successfully\n";
}
Comments
Leave a comment