【问题标题】:How to set a pointer to point to a linked list如何设置一个指向链表的指针
【发布时间】:2015-10-25 05:46:15
【问题描述】:

有没有办法建立一个指向整个链表的指针?

我需要能够将链表作为元素放入堆栈。 (堆栈也由使用节点作为元素的链表组成 - 所以链表中的链表)

我只是想知道是否有人可以提供有关如何执行此操作的示例。

谢谢!

(请仅使用 c++)

【问题讨论】:

  • 你能告诉我们你到目前为止做了什么吗?

标签: c++ pointers linked-list stack


【解决方案1】:

通常,当我使用链表并希望将链表作为一个整体引用时,我会创建一个名为 p_listp_head 的变量并将其设置为指向链表中的第一个节点。

    node* p_list = NULL;

    // Adding a new node

    // Create the node
    node* p_node_to_add = new node;
    // Set the value of the node;
    node* p_node_to_add->val = 0;
    // Point it to the rest of the linked list
    p_node_to_add->p_next_node = p_list;
    // Update the main pointer
    p_list = p_node_to_add;

    // Traversing through the linked list:
    node* p_current = p_list; // our list's "iterator"
    while(p_current != NULL)
    {
        // do something with the data in the current node
        std::cout << p_current->val << endl;
        // move on to the next node
        p_current = p_current->p_next_node;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    相关资源
    最近更新 更多