C code You are now going to create a LinkedList class that w

C++ code

You are now going to create a LinkedList class, that will work very similarly to the Stack class seen in the book (and used in the previous exercise). Then write new methods as follows:

add ( LinkedList::Link* l, int n ): will insert in the linked list, after link l, a chain of n new links. Each link will store an integer that will be set to receive, in order, a value starting from 0 until n-1. In the last link of the list always set the next pointer to be NULL in order to mark the end of the list.

print (): this method moves through the entire list printing out each integer value stored in the links.

cleanup (): updated cleanup function that will automatically delete all links in the linked list, including the data stored on each link

Your linked list struct should be named LinkedList and should be saved in a header file named LinkedList.h. The file linkedLists.cpp will be used to evaluate your struct.

My code:

output result shouldbe :

47.1
0
1
0
1
2
3
4

Solution

LinkedList.h

#ifndef LINKEDLIST
#define LINKEDLIST

#include <iostream>

struct LinkedList
{
   struct Link
   {
       void* data;
       Link* next;
      
       Link(void* dat, Link* nxt)
       {
           data = dat;
           next = nxt;
       }
   }* head;

   LinkedList(void* dat, Link* nxt)
   {
       head = new Link(dat, nxt);
   }

   void add(LinkedList::Link* l, int n)
   {
       for(int i = n; i > 0; i--)
       {
           l->next = new Link(new double(i-1), l->next);
       }
   }

   void print()
   {
       Link* current = head;
       while(current != NULL)
       {
           std::cout << *static_cast<double *>(current->data) << std::endl;
           current = current->next;
       }
   }

   void cleanup()
   {
       Link* current = head;
       while(current != NULL)
       {
           delete static_cast<double *>(current->data);
           Link* n = current->next;
           delete current;
           current = n;
       }
       head = NULL;
   }
};

#endif

C++ code You are now going to create a LinkedList class, that will work very similarly to the Stack class seen in the book (and used in the previous exercise).
C++ code You are now going to create a LinkedList class, that will work very similarly to the Stack class seen in the book (and used in the previous exercise).

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site