Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I was trying to insert value x at the beginning of the list but It doesn\'t work

ID: 673410 • Letter: I

Question

I was trying to insert value x at the beginning of the list but It doesn't work please help

my .h file

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

#include <iostream>

template <class T>
class LinkedList
{
public:
T m_data; // Data to be stored
LinkedList<T>* m_next;
LinkedList() : m_next(NULL) {}
LinkedList(const T& x, LinkedList<T>* p)
: m_data(x), m_next(p) {}
~LinkedList() {}


// Purpose: puts the data x in the front of the list
// Parameters: x is data value to inserted
// Postconditions: x is the first element of the list
void insert_front(const T& x);
};

#include "linkedlist.hpp"

#endif
----------------------------------------------------------------------------------------------------------------------------------
my .hpp file

#ifndef LINKEDLIST_HPP
#define LINKEDLIST_HPP

template <typename T>
void LinkedList <T>::insert_front(const T& x)
{

LinkedList *head=NULL;
LinkedList *tmp;

tmp->m_data = x;
tmp->m_next=head;
head=tmp;

}
#endif
------------------------------------------------------------------------------------------------------------------------------------
.cpp file
void test01() {
cout << endl << "TEST : Inserting 10 numbers to A" << endl;
for (int k=0; k<10; k++){
A.insert_front(k+1);
}
cout << A << endl;
cout << "Size of a = " << A.size() << endl;
}

Explanation / Answer

Modified code:

#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
template <class T>
class LinkedList
{
public:
   T m_data;                
   LinkedList<T>* m_next;
     static T m_objerr;
   LinkedList(): m_next(NULL)
   {
   }
   LinkedList(const T& x, LinkedList<T>* p): m_data(x), m_next(p)
   {

   }
   ~LinkedList()
   {
   }
   void insert_front(const T& x);
   int size() const;
};

#endif


#include "my.h"
template <class T>
void LinkedList <T>::insert_front(const T& x)
{
if(m_next == NULL)
     {
        m_next = new LinkedList<T>;
        m_next->m_data = x;
        m_next->m_next = NULL;
     }
     LinkedList<T> *temp;
     temp = new LinkedList<T>;
     temp->m_data = x;
     temp->m_next = m_next;
     m_next = temp;

}

#include <iostream>
using namespace std;
void test01()
{
   LinkedList<int> A;
   cout << endl << "TEST : Inserting 10 numbers to A" << endl;
   for (int k=0; k<10; k++)
   {
     A.insert_front(k+1);
   }
   for(int i =0;i<10;i++)
{
  cout<<A.m_data<<endl;
}
}
int main ()
{
  
test01();
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote