Implement a class called LinkedList class with the following functions: bullet v
ID: 3820806 • Letter: I
Question
Implement a class called LinkedList class with the following functions: bullet void insert (int n) bullet Inserts a number at the end of a Linked List bullet int size() const bullet returns the size of the Linked List bullet string toString0 const bullet prints all numbers in the linked list to a string and returns it. The numbers are separated by spaces. bullet void reverse(); bullet reverses the linked list. Your program will be tested with the following code in main (this should be your main function when you submit the code): int main () {LinkedList a; coutExplanation / Answer
#include<iostream>
#include<string>
#include<stdlib.h>
#include<sstream>
using namespace std;
//Linked List Node Structure
struct node
{
int data;
struct node *next;
};
//Linked List Class
class LinkedList
{
public:
node* head;
LinkedList();
void insert(int n);
int size() const;
string toString() const;
void reverse();
};
//Contructor for initialization
LinkedList::LinkedList(void)
{
head = NULL;
}
void LinkedList::insert(int n)
{
node* temp = (struct node*)malloc(sizeof(struct node));
temp->data = n;
temp->next = NULL;
if(head==NULL) head = temp; //no node present
else // add at the end of list
{
node*t = head;
while(t->next!=NULL)
{
t = t->next;
}
t->next = temp;
}
}
//counts elements in list
int LinkedList::size() const
{
node* temp = head;
int count = 0;
while(temp!=NULL)
{
temp = temp->next;
count++;
}
return count;
}
//converts integers to a single string
string LinkedList::toString() const
{
node* temp = head;
string result = "";
while(temp)
{
// we use stringstream to convert integer to string
int a = temp->data;
stringstream ss;
ss << a;
string str = ss.str();
result = result+str+" ";
temp = temp->next;
}
return result;
}
// reverse the LinkedList by using 3 pointers in linear time
void LinkedList::reverse()
{
node* prev = NULL;
node* current = head;
node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}
int main()
{
LinkedList a;
cout<<"size of a="<<a.size()<<endl;
a.insert(1);
a.insert(2);
a.insert(4);
a.insert(3);
cout<<"size of a="<<a.size()<<endl;
cout<<a.toString()<<endl;
a.reverse();
cout<<"size of a="<<a.size()<<endl;
cout<<a.toString()<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.