【发布时间】:2013-08-01 12:49:04
【问题描述】:
我有一个代码,它似乎可以工作,但我无法获取存储在第一个和最后一个节点之间的链表中的值,是否跳过了它们之间的指针?并且取消引用这些跳过的指针会给我一个段错误,这是代码
#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);
}
}
- 在打印值时为什么会跳过这些指针(节点)?
- 被指向的节点之间的中间是否被破坏?如果是这样,评论析构函数应该可以解决问题,对吧?
我做错了什么?
【问题讨论】:
-
一方面,您没有使用一致的缩进。所以没有人有太多机会阅读你的代码。
-
root->newnode(num, tpo);从不更新root或tpo所以每个新值都会替换前一个 -
谢谢@FredLarson,对不起,我会考虑的。
标签: c++ class pointers linked-list