首页 > 解决方案 > 为什么我的链表实现不起作用?

问题描述

编译后 - 当 cmdl 弹出时 - 它不会终止并像等待输入一样等待

#include <bits/stdc++.h>

using namespace std;

struct node{
    int data;
    node *next;
};

class LinkedList{
private:
    struct node *head;
    struct node *tail;
public:
    LinkedList(int val1,int val2){
        head->next = tail;
        head->data = val1;
        //tail->next = NULL;
        //tail->data = val2;
    }
    add(int val){
        struct node *n = new node;
        n->next = head->next;
        head->next = n;
        n->data = val;
    }
    display(){
        struct node *ptr = head;
        while(ptr->next!=NULL){
            cout<<ptr->data;
            ptr = ptr->next;
        }
    }
};

int main(){
    LinkedList l(1,3);
    for(int i = 0;i<5;i++) l.add(i);
    l.display();
}

是什么阻止了代码按预期执行?我尝试了一些内置函数来测试代码,但是它们都没有响应调用并生效。

标签: c++pointers

解决方案


运行此代码时出现访问冲突。

添加

head = new node;

在您的构造函数的开头修复了这个问题。

我也会像这样显式地将 head 和 tail 初始化为 null

private:
     struct node *head = NULL;
     struct node *tail = NULL;

否则,它们将充满垃圾值,您可能会在显示代码中获得无限循环。


推荐阅读