Reputation: 1015
I am trying to implement a basic singly linked list. In that, I am trying to insert from head. Then I tried to print the inserted data. My code is below:
#include<iostream>
using namespace std;
template<class T>
class Node
{
public:
T data;
Node<T> *next;
Node():data(T()),next(NULL)
{}
};
template<class T>
class SinglyinkedList
{
public:
Node<T> *head;
SinglyinkedList():head(NULL)
{}
void insertFromHead(T data)
{
Node<T> *temp;
temp->data = data;
temp->next = head;
head = temp;
}
void printLinkedist()
{
Node<T> *temp;
temp = head;
while(temp != NULL)
{
cout <<"Hi";
cout << temp->data;
temp = temp->next;
}
}
};
int main()
{
SinglyinkedList<int> list;
list.insertFromHead(10);
list.insertFromHead(20);
list.insertFromHead(30);
list.insertFromHead(40);
list.printLinkedist();
return 0;
}
But When I print linked list it just stuck in while loop and printing same value again and again. Can anyone help why I am stuck in loop?
Upvotes: 2
Views: 161
Reputation: 66371
Linked-list code usually contains one use of new
for each node, and you forgot yours.
This means that you were using an uninitialised pointer, which is undefined.
Add the missing object:
void insertFromHead(T data)
{
Node<T> *temp = new Node<T>;
temp->data = data;
temp->next = head;
head = temp;
}
If you add a constructor to Node
,
Node(const T& d, Node<T>* n): data(d), next(n) {}
you can shorten it a bit, too:
void insertFromHead(const T& data)
{
head = new Node<T>(data, head);
}
Upvotes: 2
Reputation: 2278
Your problem is likely here:
Node<T> *temp;
temp->data = data;
temp is not initialized to anything before you attempt to dereference it
Upvotes: 0
Reputation: 953
You are trying working with uninitialized object
Node<T> *temp;
temp->data = data;
You got such kind of undefined behavior. Just use:
void insertFromHead( T data )
{
Node<T> *temp = new Node<T>();
temp->data = data;
temp->next = head;
head = temp;
}
An it will solve your problem
Upvotes: 2