【发布时间】:2015-10-25 05:46:15
【问题描述】:
有没有办法建立一个指向整个链表的指针?
我需要能够将链表作为元素放入堆栈。 (堆栈也由使用节点作为元素的链表组成 - 所以链表中的链表)
我只是想知道是否有人可以提供有关如何执行此操作的示例。
谢谢!
(请仅使用 c++)
【问题讨论】:
-
你能告诉我们你到目前为止做了什么吗?
标签: c++ pointers linked-list stack
有没有办法建立一个指向整个链表的指针?
我需要能够将链表作为元素放入堆栈。 (堆栈也由使用节点作为元素的链表组成 - 所以链表中的链表)
我只是想知道是否有人可以提供有关如何执行此操作的示例。
谢谢!
(请仅使用 c++)
【问题讨论】:
标签: c++ pointers linked-list stack
通常,当我使用链表并希望将链表作为一个整体引用时,我会创建一个名为 p_list 或 p_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;
}
【讨论】: