简体   繁体   中英

Linked List - pointers

I created a linked list and when I tried to print values of the nodes and used NULL as a bound, it didn't work. For example:

#include <iostream>

typedef struct Node;
typedef Node* Node_ptr;
struct Node
{
    int i;
    Node_ptr next;
};

int main()
{
    Node_ptr ptr, head;
    ptr = new Node;
    head = ptr;

    // load
    for(int j = 0; j < 4; j++)
    {
        ptr->next = new Node;
        ptr->i = j;
        ptr = ptr->next;
    }

    // print
    ptr = head;
    while(ptr->next != NULL)
    {
        std::cout << "print: " << ptr->i << std::endl;
        ptr = ptr->next;
    }
}

However, when I run this code, the code gets stuck in an endless loop in the while loop. It never understands that the linked list is only 5 nodes long, it just keeps on going. I can't understand why that happens.

You probably just need to initialize your pointers (to NULL), otherwise they'll just contain garbage, and will thus also appear as being valid pointers.

For instance:

for(j = 0; j < 4; j++)
{
   ptr->next = new Node;
   (ptr->next)->next = NULL;
   ptr->i = j;
   ptr = ptr->next;
}

Try value initializing your Node :

ptr = new Node();

instead of

ptr = new Node;

Otherwise, you'll just have garbage in the members.

while(ptr->next != NULL)

You clearly coded it to continue until ptr->next is NULL . Maybe you should set ptr->next to NULL for at least one item in the list? This is why it is common in C to memset(&object, 0, sizeof(object)); , or in C++ to have a constructor.

typedef struct Node
{
  int i;
  Node* next;
  Node() : i(0), next(NULL) {} //prevents this problem
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM