使用类的链接列表
Linked list using Class
我有一个代码,它似乎在工作,但我无法获得存储在第一个节点和最后一个节点之间的链表中的值,中间的指针被跳过了吗?取消引用这些跳过的指针会给我一个segfault,这是代码
#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);
}
}
- 在打印值时,为什么它会跳过中间的指针(节点)
- 指向的中间节点是否已销毁?如果是这样,那么对析构函数进行注释就可以了,对吧
我做错了什么?
1)当您调用更多值时,您总是覆盖列表中的第二个元素。您需要将newnode()
的签名更改为newnode(int a, list*& tmp)
。
稍后编辑:另一种方法是使用以下签名list* newnode(int a, list* tmp)
,并在函数末尾使用return tmp;
。然后,在主循环中,您将得到tpo = root->newnode(num, tpo);
。这样CCD_ 6将总是指向下一个元素。
2) 此外,为了释放内存,list
的析构函数不应该做任何特别的事情。我建议您在类中创建一个静态方法来删除列表。类似这样的东西:
public:
static void deleteList(list*& root)
{
list* tmp = root;
while (tmp)
{
tmp = root->next;
delete root;
root = NULL;
root = tmp;
}
};
并将其称为list::deleteList(root);
您总是将root
提交给newnode(与分配给tpo
的一样),从而生成一个包含两个元素和任意数量泄漏内存的列表
一个全面的链表实现,查看下面的链接:
http://www.bitsbyta.com/2011/02/how-to-add-node-at-end-of-linked-list-c.html
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表