简体   繁体   English

链表-指针

[英]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. 我创建了一个链表,当我尝试打印节点的值并使用NULL作为绑定时,它不起作用。 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. 但是,当我运行此代码时,代码陷入while循环的无限循环中。 It never understands that the linked list is only 5 nodes long, it just keeps on going. 它永远不会理解链表只有5个节点,它一直在继续。 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. 您可能只需要初始化指针(为NULL),否则它们将只包含垃圾,因此也将显示为有效指针。

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 : 尝试值初始化您的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 . 您清楚地对其进行了编码,直到ptr->nextNULL为止。 Maybe you should set ptr->next to NULL for at least one item in the list? 也许您应该为列表中的至少一项将ptr->next设置为NULL This is why it is common in C to memset(&object, 0, sizeof(object)); 这就是为什么在C普遍使用memset(&object, 0, sizeof(object)); , or in C++ to have a constructor. ,或在C++中具有构造函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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