打印功能无法正常工作 - 链表
Print function isn't working properly- Linked list
我是数据结构的新手,我正在尝试编写将节点添加到链表开头的代码。每次用户进入新节点后,程序都应该显示更新链表,但我的程序只显示当前输入的节点。
代码如下: -
#include<iostream.h>
#include<conio.h>
struct Node
{
int data;
Node* next;
};
struct Node* head;
void Insert(int x)
{
Node* temp=new Node();
temp->data=x;
temp->next=NULL;
head=temp;
}
void Print()
{
struct Node* temp=head;
cout<<"List is: ";
while(temp!=NULL)
{
cout<<temp->data;
temp=temp->next;
}
cout<<"n";
}
void main()
{
head=NULL;
clrscr();
cout<<"How many numbers?n";
int n,x,i;
cin>>n;
for(i=0; i<n; i++)
{
cout<<"Enter the number n";
cin>>x;
Insert(x);
Print();
}
getch();
}
你的Insert
方法错了。您需要将head
分配给next
:
void Insert(int x)
{
Node* temp=new Node();
temp->data=x;
temp->next=head;
head=temp;
}
然后,这将正确链接您的列表。
您的Insert
函数是错误的。您需要使用这样的东西才能在列表末尾添加新项目:
void InsertAtTheEnd(int x) {
Node* temp = new Node();
temp->data=x;
temp->next=NULL;
if (NULL == head) {
head = temp;
} else {
Node *tmp = head;
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = temp;
}
}
这会将它们添加到开头:
void InsertAtTheBeginning(int x) {
Node* temp=new Node();
temp->data=x;
temp->next=head;
head=temp;
}
现场查看
相关文章:
- 链表c++插入,所有情况都已检查,但没有任何工作
- 链表中的显示功能无法正常工作
- 打印功能无法正常工作 - 链表
- 有人可以向我解释这个链表是如何工作的吗?
- 双向链表 std::unique_ptr 类在节点删除时无法按预期工作
- 创建链表,但无法按 CPP 的预期工作
- 程序 使用链表插入数据时停止工作
- 如何与朋友操作员一起在链表下面工作
- 链表中的交换节点如何工作
- C++ 由于某种原因,我无法让模板在链表中工作,我敢打赌这是一个简单的错误,但我就是不明白
- 链表无法正常工作,而是更新了头
- 如何使链表与类的多个实例一起工作
- 链表中的头指针被神奇地分配了,不应该工作,但确实工作
- 插入到链表的尾部,C++无法正常工作
- 链表中的指针没有按预期工作
- 从链表中删除节点无法正常工作
- 链表不能正常工作
- c++删除链表不能正常工作
- 双链表函数的一部分不能正常工作
- 使自定义链表与pod一起工作