[英]Linked List Head C++
I am making a simple linked list for a data structures class and am having trouble understanding how the head pointer is supposed to work.我正在为数据结构类制作一个简单的链表,但在理解头指针应该如何工作时遇到了麻烦。
I have我有
template <typename E>
class SSLL{
template<typename E>
struct Node {
E data;
Node* next;
};
public:
template <typename E>
SSLL();
void push_front(E element);
private:
Node<E> * head;
Node<E> * tail;
};
template <typename E>
SSLL<E>::SSLL() {
head = NULL;
tail = NULL;
}
template <typename E>
void SSLL<E>::push_front(E element) {
Node<E> * n = new Node<E>;
n->data = element;
n->next = head;
head = n;
if (!tail) {
tail = n;
}
}
However, doesn't this make head the first element in the list instead of a pointer to the first element.但是,这不会使 head 成为列表中的第一个元素而不是指向第一个元素的指针。
I tried to do change push_front(E element) to this but am getting null pointer errors.我尝试将 push_front(E element) 更改为此,但出现空指针错误。
template <typename E>
void SSLL<E>::push_front(E element) {
Node<E> * n = new Node<E>;
n->data = element;
n->next = head->next;
head->next = n;
if (!tail) {
tail->next = n;
}
}
All the examples I find online have head = n, but I still have trouble understanding why it is like that instead of head->next = n.我在网上找到的所有例子都有 head = n,但我仍然无法理解为什么是这样而不是 head->next = n。
Thank you.谢谢。
In most forms of linked lists, the head pointer points to the first node in the list or is null:在大多数形式的链表中,头指针指向链表的第一个节点或者为空:
+---+ +---+ +--+
head --> | A | --> | B | --> |/0|
+---+ +---+ +--+
^
|
tail ----------------+
Many beginners confuse a list with a node.许多初学者将列表与节点混淆。 A node is the object containing the data.
节点是包含数据的对象。 A list is a collection of nodes.
列表是节点的集合。
Pushing at the head顶着头
Inserting at the front requires the following steps:在前面插入需要以下步骤:
1) Making new node point to head node: 1) 使新节点指向头节点:
+---+
p_new -->| C |
+---+
|
V
+---+ +---+ +--+
head --> | A | --> | B | --> |/0|
+---+ +---+ +--+
2) Making the head point to the new node: 2)使头指向新节点:
+---+
p_new -->| C |
head -->| |
+---+
|
V
+---+ +---+ +--+
| A | --> | B | --> |/0|
+---+ +---+ +--+
In C++, this would look like:在 C++ 中,这看起来像:
Node * p_node = new Node;
p_node->next = head; // Step 1.
head = p_node; // Step 2.
We can make new Head in c++ by simple code :我们可以通过简单的代码在 C++ 中创建新的 Head:
ListNode* dummy = new ListNode(0);
dummy->next = head;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.