Please in C++. Create a LinkedList class where you implement a linked-list. Incl
ID: 3691191 • Letter: P
Question
Please in C++.
Create a LinkedList class where you implement a linked-list. Include your node implementation in the class file (just a header file for the class is fine, along with the main function .cpp file). The node is a struct that has a data variable, and a pointer of node type that points to the next node. The LinkedList class must have three protected member variables: any integer variable to keep track of the size, and two node pointers to keep track of the beginning and end of the list. It must have a default constructor which initializes the size, and assigns the two pointers to nullptr. It must have a working destructor that accurately frees all of the memory in the list, by traversing the list and deleting each node. It must have a public member function to print the entire list. It must have a public member function push(), to add an item to the end of the list, being sure to update the pointers and size variable correctly.
Create a test function where you print the empty list, add a few values, and then print again
Explanation / Answer
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node
{
int info;
struct node *next;
};
class LinkedList
{
public:
int size;
node *start,*end;
node* create_node(int);
void push();
void print();
LinkedList()
{
start = NULL;
end = NULL;
}
~LinkedList();
};
node *LinkedList::create_node(int value)
{
struct node *temp;
temp = new(struct node);
if (temp == NULL)
{
cout<<"Memory not allocated "<<endl;
return 0;
}
else
{
temp->info = value;
temp->next = NULL;
return temp;
}
}
LinkedList::~LinkedList(){
delete start;
delete end;
}
void LinkedList::push()
{
int value;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp;
temp = create_node(value);
temp->next = NULL;
if(start==NULL){
start = temp;
end = temp;
size = 1;
}else{
end->next = temp;
end = end->next;
size = size + 1;
}
cout<<"Element Inserted at last"<<endl;
}
void LinkedList::print()
{
struct node *temp;
if (start == NULL)
{
cout<<"The List is Empty"<<endl;
return;
}
temp = start;
cout<<"Elements of list are: "<<endl;
while (temp != NULL)
{
cout<<temp->info<<"->";
temp = temp->next;
}
cout<<"NULL"<<endl;
}
int main(){
LinkedList ll;
ll.push();
ll.print();
ll.push();
ll.push();
ll.print();
}