【发布时间】:2020-09-29 17:35:00
【问题描述】:
这里我只是想打印我创建的链表的元素,但它以反向顺序打印列表。看起来代码有错误。帮我解决它 每次我们输入要插入链表的元素时,push 函数都会将节点添加到链表中。我已经传递了头和数据的引用。每次调用 push 函数时都会动态创建一个节点。我这里用的是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_ref)->next=new_node
标签: c++ data-structures linked-list singly-linked-list