在这里,我只是想打印我创建的链表的元素,但它是以反向顺序打印链表的。似乎代码中有错误。请帮我解决
每当我们输入要插入链表中的元素时,push函数都会将节点添加到链表中。我已经传递了head和data的引用。每次调用推功能时,都会动态创建一个节点。我在这里使用c++。
#include<iostream>
using namespace std;
class node{
public:
int data;
node* next;
};
//creating linked list
void push(node** head_ref,int new_data) //passing address of head and data to put in list
{
node* new_node=new node(); //new node created
new_node->data=new_data; //data inserted
new_node->next=*(head_ref);
*(head_ref)=new_node;
}
int main()
{
node* head=NULL;
int n;
cin>>n; //number of elements in linked list
for(int i=0;i<n;i++)
{
int val;
cin>>val;
push(&head,val); //push function which creates a linked list
}
//while loop for printing elements of linked list
while(head!=NULL)
{
cout<<head->data;
head=head->next;
}
return 0;
}
最佳答案
当前您正在做的是将每个节点分配为当前head的前任元素,因此最终您的head将是您添加的最新元素,其后继元素,倒数第二个元素,其后继元素,最后一个第三元素等,因此导致反向列表。
您应该将新节点分配为当前“头”的后继节点,如下所示:
void push(node** tail_ref,int new_data) //passing address of tail and data to put in list
{
node* new_node=new node(); //new node created
new_node->data=new_data; //data inserted
(*tail_ref)->next= new_node;
*(tail_ref)=new_node;
}
请注意,在上面的代码段中,我将
head_ref
重命名为tail_ref
,它更好地描述了指针实际代表的内容:指向列表当前最后一个元素的指针,因此指向列表的尾部。当然,您将需要保存指向第一个元素的指针。否则,您将无法遍历链接列表。
关于c++ - 打印链接列表的元素,但是打印相反的C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62301273/