无法显示链表的值?
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;
}
}
在主程序头为空,因此在插入函数中由于检查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;
相关文章:
- 链表中的显示功能无法正常工作
- 在链表中的第 n 位插入显示分割错误
- 仅显示链表的最后一个元素
- 查找显示链表时出现的错误
- 链表显示垃圾字符
- 无法弄清楚如何使用 c++ 中的链表按从 a 到 z 的顺序显示字母
- 我已经做了一个程序来使用队列链C++表显示学生姓名和身高,现在我想以我不知道如何显示的顺序显示它
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?
- 双向链表问题 - 包含项目但不显示
- 为什么我的C++代码在以下打印链表的代码片段中显示分段错误?
- 追加到双向链表并显示
- 为什么我无法显示我的链表?
- 递归解决方案,用于显示线性链表数组
- 尝试反转链表时显示分段错误
- 如何在不使用 C++ 函数的情况下显示链表中的元素
- 显示来自链表的稀疏矩阵,该链表仅存储了非零元素
- 无法显示链表的值?
- 我在显示链表时遇到问题
- 尝试拆分循环链表.显示输出但崩溃.在 IDEone 中显示运行时错误
- 链表显示;缺少..但事实并非如此