仅显示链表的最后一个元素

Only the last element of the linked list is displayed

本文关键字:最后一个 元素 链表 显示      更新时间:2023-10-16

我一直在尝试用 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;
}
}
#include<iostream>
using namespace std;
class node{
public:
int data;
node *next;
node(int x)
{
data=x;
next=nullptr;
}
}*head,*newnode,*temp;
node* create(int);
void display(node*);
int main()
{
int n;
cout<<"Enter the no of nodes: ";
cin>>n;
head=create(n);
display(head);
return 0;
}
node *create(int n)
{

for(int i=0;i<n;i++)
{
int x;
cout<<"Enter the value of node "<<i+1<<": ";
cin>>x;
newnode=new node(x);
if(i==0)
{
head=temp=newnode;
}
else
{
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();

把所有东西放在一起

https://repl.it/repls/MedicalEquatorialFlashmemory#main.cpp