Home Stuck in infinite while loop while printing values from a custom linked list
Reply: 3

Stuck in infinite while loop while printing values from a custom linked list

Devendra Verma
1#
Devendra Verma Published in 2017-12-07 16:05:55Z

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?

molbdnilo
2#
molbdnilo Reply to 2017-12-07 16:11:07Z

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);
}
arturx64
3#
arturx64 Reply to 2017-12-07 16:09:30Z

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

Justin Randall
4#
Justin Randall Reply to 2017-12-07 16:09:33Z

Your problem is likely here:

      Node<T> *temp;
      temp->data = data;

temp is not initialized to anything before you attempt to dereference it

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.33197 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO