无法显示链表的值?

Unable to display the values of Linked List?

本文关键字:链表 显示      更新时间:2023-10-16

这是我的C++程序,用于在链表的开头插入值。该程序的逻辑对我来说似乎很好,但它无法显示列表的值。我想问题出在 Print() 函数中。请帮忙!

#include<iostream.h>
struct Node
{
int data;
Node* next;
};
struct Node* head;
void Insert(int x)
{
Node *temp=new Node();
temp ->data=x;
temp ->next=NULL;
if(head!=NULL)
{
temp->next=head;
head=temp;
}
}
void Print()
{
Node *temp=head;
cout<<"List is:";
do
{
cout<<temp->data<<"->";
temp=temp->next;
}while(temp!=NULL);
cout<<endl;
}
int main()
{
int n,i,x;
head=NULL;
cout<<"How many numbers n";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter the number n";
cin>>x;
Insert(x);
Print();
}
return 0;
}
void Insert(int x)
{
Node *temp=new Node();
temp ->data=x;
temp ->next=NULL;
if(head!=NULL)
{
temp->next=head;
head=temp;
}
}

在主程序头为空,因此在插入函数中由于检查if(head!=NULL)它永远不会更新。

正确的解决方案是

#include<iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
struct Node* head;
void Insert(int x)
{
Node *temp=new Node();
temp ->data=x;
temp ->next=NULL;
if(temp!=NULL)
{
temp->next=head;
head=temp;
}
}
void Print()
{
Node *temp=head;
cout<<"List is:";
do
{
cout<<temp->data<<"->";
temp=temp->next;
}while(temp!=NULL);
cout<<endl;
}
int main()
{
int n,i,x;
head=NULL;
cout<<"How many numbers n";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter the number n";
cin>>x;
Insert(x);
}
Print();
return 0;
}

您需要更新head由于条件检查if(head!=NULL)NULL从未更改。

改变

if(head!=NULL)
{
temp->next=head;
head=temp;
}

if(head!=NULL)
{
temp->next=head;
}
head=temp;