c++ - 创建链表,但不能按 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;
}
该程序正在完美编译,但是在运行时它会停止并且如果我将插入函数放入循环中它就不起作用,那么问题就会出现,否则它运行良好