c++ - 只显示链表的最后一个元素
问题描述
我一直在尝试在 C++ 中创建一个链表。但只显示链表的最后一个元素。我已经搜索了错误,但我找不到它。我已经实现了从 c 语言中学到的逻辑。所有节点都正确连接。但我仍然找不到错误。此逻辑适用于 c 语言。请帮忙。
#include<iostream>
using namespace std;
class node{
public:
int data;
node *next;
}*head,*newnode,*temp;
node* getnode();
node* create(int);
void display(node*);
int main()
{
int n;
head=getnode();
cout<<"Enter the no of nodes: ";
cin>>n;
head=create(n);
display(head);
return 0;
}
node *getnode()
{
head=new node();
head->next=nullptr;
return(head);
}
node *create(int n)
{
head=getnode();
cout<<"Enter the value of node 1: ";
cin>>head->data;
temp=getnode();
temp=head;
for(int i=1;i<n;i++)
{
newnode=getnode();
cout<<"Enter the value of node "<<i+1<<": ";
cin>>newnode->data;
newnode->next=nullptr;
temp->next=newnode;
temp=newnode;
}
return(head);
}
void display(node *head)
{
while(head!=nullptr)
{
cout<<"->"<<head->data;
head=head->next;
}
}
解决方案
使用局部变量
*head,*newnode,*temp
是全局变量。每次调用函数时,都会覆盖它们。使它们成为局部变量。
内存泄漏
您还使用以下方法在 main() 中泄漏内存:
head=getnode();
在 create() 中:
temp=getnode();
把它们放在一起
推荐阅读
- android - 使用 Build.VERSION_CODES 是一种好习惯吗?如果是这样,为什么?
- jquery - Jquery在第一次访问时不适用
- django - python social auth 更改引用地址
- delphi - Delphi Indy:突然遇到 14094410:SSLroutines:ssl3_read_bytes:sslv3 alert handshake failure
- python - 词优化器
- python - 带有选择字段的烧瓶链式下拉菜单不是有效的选择
- entity-framework - 在实体框架中添加与同一张表的第二个一对一关系
- javascript - React Router 4 - 组件重新安装而不是重新渲染
- javascript - 如何在我的数组分组后在我的数组中连接/插入元素?
- database - 如何检查多边形是否位于 JaguarDB 中的线串之上?