c++ - 打印链接列表的元素,但是打印相反的C++

标签 c++ data-structures linked-list singly-linked-list

在这里,我只是想打印我创建的链表的元素,但它是以反向顺序打印链表的。似乎代码中有错误。请帮我解决
每当我们输入要插入链表中的元素时,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/

相关文章:

data-structures - 在 B 树的上下文中, "key"究竟意味着什么?

c - 想制作删除第一个节点的链表函数

C 插入排序 - 实现

c++ - OpenSSL-多线程环境-C++

c++ - 诊断 Visual C++ 链接器

c++ - 存储和重用 vector 迭代器值是否安全?

python - 交换存储在元组中的两个列表的位置

c - C 中的单链表

c++ - 再次获取 std::map 会更改前一个迭代器

C++:将 std::set_union() 输出存储在 std::multiset 中