首页 > 解决方案 > 创建链表,但不能按 cpp 的预期工作

问题描述

#include <iostream>
using namespace std;

struct Node{
    int data;
    Node* next=NULL;
};
class list{
    Node *head,*tail;
    public:
        void insert(int data){
            Node *node =new Node;
            node->data=data;
            node->next=NULL;
            if(head==NULL){
                head=node;
                tail=node;
            }else{
                tail->next=node;
                tail=tail->next;
            }
        }
        void show(){
            Node *n=head;
            while(n->next!=NULL){
                cout<<n->data<<" ";
                n=n->next;
            }
            cout<<n->data<<endl;
        }
};

int main(){
    list x;
    int n;
    for(int i=0;i<10;i++){
        cin>>n;
        x.insert(n);
    }
    x.show();

    return 0;
}

该程序正在完美编译,但是在运行时它会停止并且如果我将插入函数放入循环中它就不起作用,那么问题就会出现,否则它运行良好

标签: c++

解决方案


当您声明一个指针时,它不一定具有默认值NULL

相关问题

初始化headtail使用NULL,程序将成功运行。


推荐阅读