【问题标题】:Unable to display the values of Linked List?无法显示链表的值?
【发布时间】:2017-07-28 16:48:23
【问题描述】:

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

【问题讨论】:

  • 调试器是解决此类问题的正确工具。 询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
  • 请正确格式化您的代码(就像您的 C++ 教科书中的示例一样)。

标签: c++ pointers linked-list iterator insertion


【解决方案1】:
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;
}

【讨论】:

  • @BhargabKakati,您可以尝试实施发布到您原始问题的建议,看看它是否解决了您的问题。
  • 回答时,请至少正确格式化您的代码。
【解决方案2】:

由于if(head!=NULL) 条件检查,您需要更新head,它不会从初始NULL 更改。

改变

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2021-10-13
    • 2020-01-26
    • 2021-01-19
    • 1970-01-01
    • 2013-02-07
    相关资源
    最近更新 更多