c++ - 链表 C++ 的错误打印

标签 c++

请你解释一下,为什么函数“print”在这段代码中无限打印一个相同的数字?

显然,链表构造正确,但在逐步调试时,它停留在“打印”功能上。

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

struct num {
    int n;
    num* next;};

void add (num*&head, int size) {
    num*newnode = new num;
    for (int i = 0; i<size; i++) {
        newnode->n = rand()%100;
        newnode->next = head;
        head = newnode;}
}

void print (num*head) {
    num*temp = head;
    while (temp != 0) {
        cout << temp->n << endl;
        temp = temp ->next;}}

void del (num*&head) {
    num*temp = 0;
    while (head!=0){
        temp = head;
        head = head->next;
        delete temp;}}

int main () {
srand ((unsigned int)time(0));
num*head = 0;
add (head, 10);
print (head);
del (head);
cin.get();
cin.ignore();
}

最佳答案

问题出在添加功能上。您不是在创建新节点。而是修改同一个节点并将其指向自身。

这样改

    for (int i = 0; i<size; i++) {
        newnode = new num; //new node
        newnode->n = rand()%100;
        newnode->next = head;
        head = newnode;}

关于c++ - 链表 C++ 的错误打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28646114/

相关文章:

c++ - 为您的 C++ 库和严格的别名提供 C API

c++ - unordered_map 在实践中真的比 map 快吗?

c++ - 零星碰撞检测

c++ - 同一台计算机上的 UDP 连接。 1 个服务器。多个客户端

结构和类之间的 C++ 区别 VS2015 中的初始化

C++ 重载 getter 两次,一次返回指针,一次返回 const 引用,失败

c++ - 如何确保已读取所有管道缓冲区?

c++ - 在 C++ 中检查是否存在时出错

c++ - 让不同的输入做不同的事情?

c++ - Visual Studio Code 找不到我在 C++ 中声明和定义的类