gpt4 book ai didi

c++ - 仅显示链接列表的最后一个元素

转载 作者:行者123 更新时间:2023-12-02 10:14:09 25 4
gpt4 key购买 nike

我一直试图在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;
}
}
Ive刚刚创建了一个用于创建新节点的构造函数,并使用了临时指针来跟踪列表中最后插入的元素。请记住,始终最好固定头部指针,并使用另一个指针进行遍历。您的代码的问题是,您的头指针始终指向最后插入的元素。

关于c++ - 仅显示链接列表的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62529045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com