我有一个代码,它似乎可以工作,但我无法获取存储在第一个节点和最后一个节点之间的链表中的值,是否跳过了中间的指针?取消引用这些跳过的指针会给我一个段错误,这是代码
#include<iostream>
#include <new>
using namespace std;
class list{
int value;
list* next;
public:
list(int a=0, list* b=0) {value=a;next=b;}
//~list() {delete next;}
void newnode(int a, list* tmp) {
tmp->next=new list;
tmp=tmp->next;
cout<<"Address of next: "<<tmp<<'\n';
tmp->value=a;
}
void printlist (list* regist){
list* tmp;
tmp=regist;
cout<<tmp->value<<'\n';
while(tmp->next != 0){
tmp=tmp->next;
cout<<tmp->value<<'\n';
cout<<"Address of next: "<<tmp<<'\n';
}
}
};
int main() {
int first;
cout<<"Enter value for origin: \n";
cin>>first;
list* root=new list(first);
list* tpo=root;
cout<<"How many numbers to add? \n";
int choice;
cin>>choice;
int num;
while(choice) {
cout<<"Enter value: \n";
cin>>num;
root->newnode(num, tpo);
choice--;
}
cout<<"Do you want me to show you these values, type 1 for yes and 0 for no: \n";
cin>>choice;
if(choice) {
root->printlist(root);
}
}
- 在打印值时,为什么它会跳过这些指针(节点)?
- 节点之间的中间是否被指向被破坏?如果是这样,评论析构函数应该可以解决问题,对吗?
我究竟做错了什么?