尾部指向最后一个节点
Tail pointing at the last node?
void IntList::push_front(int value){
IntNode *holder = new IntNode(value);
holder -> next = head;
head = holder;
if(head == 0){
tail = head;
}
tail = holder;
}
页眉
#ifndef INTLIST_H
#define INTLIST_H
struct IntNode{
int data;
IntNode *next;
IntNode(int data) : data(data), next(0) {}
};
class IntList{
private:
IntNode *head;
IntNode *tail;
public:
void push_front(int value);
};
#endif
如何让尾部指向最后一个尾部节点? 我有 if 语句,因此如果列表为空,它设置为 0。
head = holder;
if(head == 0){
tail = head;
}
上面的步骤顺序错误:您将 head 设置为 holder(永远不会为 0,因为如果内存分配失败,您将获得异常,如果它有效,您将获得指向分配节点的指针),然后测试头部是否仍然等于 0。
你可以颠倒他们的顺序,但恕我直言,无论如何直接测试尾巴更干净:
head = holder;
if (tail == nullptr)
tail = head;
在 C++11 之前的编译器上,您可能没有nullptr
- 只需使用 NULL 或 0 或更改为 if (!tail)
。
相关文章:
- 删除链接列表中剩余的最后一个节点
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- 删除最后一个节点,并将尾部更新到最后一个节点
- 计算列表中与线性链接列表中最后一个节点具有相同数据的节点的数量
- 如何在QT中获取XML文件的最后一个节点
- 交换C 中的第一个和最后一个节点
- 尾部指向最后一个节点
- 链表只打印添加新节点后的最后一个元素
- 从end()函数返回的迭代器中获取BST的最后一个节点
- 删除链接列表中的最后一个节点
- 链表:无法访问最后一个节点,获取 R6010(C++、VS2010)
- 删除双向链表 (C++) 的最后一个节点
- 单链表删除最后一个节点
- 打印链表仅打印最后一个节点
- 删除链接列表的最后一个节点
- 是否可以删除链接列表中的最后一个节点
- 从链表c++中删除最后一个节点
- 更新指向链表中最后一个节点的指针
- 使用递归在单个链表中查找第n到最后一个节点
- 删除列表错误中的最后一个节点