尾部指向最后一个节点

Tail pointing at the last node?

本文关键字:节点 最后一个 尾部      更新时间:2023-10-16
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)