无法显示链表的值?

Unable to display the values of Linked List?

这是我的 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;
}
}

在主程序中 head 为空,因此在插入函数中它永远不会更新,因为 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;