为什么此代码用于单个链接列表不起作用
Why is this code for single linked list not working?
作为初学者,我尝试了这个单个链接列表程序以接受并首先显示到最后一个元素。在第一个元素中。我对语言并不熟悉,对指针概念是新手。这是一项作业。
#include <iostream>
using namespace std;
struct node
{
int data;
node* next;
};
class alpha
{
public:
node* head;
node* last;
node* n;
node* p;
int x;
char ch;
void input()
{
cout << "Enter the element..";
cin >> x;
insert(x);
cout << "Do you want to add more?";
cin >> ch;
if (ch == 'y')
{
input();
}
else
{
display();
}
}
void insert(int x1)
{
n = new node;
n->data = x1;
if (head == NULL)
{
head = n;
last = n;
}
else
{
n->next = NULL;
last->next = n;
last = n;
}
}
void display()
{
p = head;
while (p != NULL)
{
cout << p->data;
p = p->next;
}
}
};
int main()
{
alpha o;
o.input();
return 0;
}
已经指出的大错误是构造函数没有初始化。我也建议将一些数据成员移至私有,并将其中一些数据成员置于本地。
#include <iostream>
using namespace std;
struct node
{
int data;
node* next;
};
class alpha
{
private:
node* head;
node* last;
public:
alpha() {
head = NULL;
last = NULL;
}
void input()
{
int x;
char ch;
cout << "Enter the element..";
cin >> x;
insert(x);
cout << "Do you want to add more?";
cin >> ch;
if (ch == 'y')
{
input();
}
else
{
display();
}
}
void insert(int x1)
{
node* n = new node;
n->data = x1;
if (head == NULL)
{
head = n;
last = n;
}
else
{
n->next = NULL;
last->next = n;
last = n;
}
}
void display()
{
node* p = head;
while (p != NULL)
{
cout << p->data;
p = p->next;
}
}
};
int main()
{
alpha o;
o.input();
return 0;
}
正如某人建议的那样,请实现destructor〜alpha((,以避免泄漏节点实例。
相关文章:
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表