打印功能无法正常工作 - 链表

Print function isn't working properly- Linked list

本文关键字:工作 链表 常工作 功能 打印      更新时间:2023-10-16

我是数据结构的新手,我正在尝试编写将节点添加到链表开头的代码。每次用户进入新节点后,程序都应该显示更新链表,但我的程序只显示当前输入的节点。

代码如下: -

#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;
}

现场查看