队列类中删除节点的过程

时间:2016-02-06 21:50:28

标签: c++ c++11

此代码复制自c ++ primer plus。我想一些  出队功能中的步骤是不必要的。但这本书  说它很重要。我不明白。我希望有人可以向我展示更详细的解释。这是队列的定义。

typedef unsigned long Item;
class Queue
    {
    private:
        struct Node{ Item item; struct Node * next; };
        enum{ Q_SIZE = 10 };
        Node * front;
        Node * rear;
        int items;             // the number of item in the queue
        const int qsize;
        Queue(const Queue & q) :qsize(0){};
        Queue & operator=(const Queue & q){ return *this; }
        Queue & operator=(const Queue & q){ return *this; }
    public:
        Queue(int qs = Q_SIZE);
        ~Queue();
        bool isempty()const;
        bool isfull()const;
        int queuecount()const;
        bool enqueue(const Item & item);
        bool dequeue(Item & item);
    };

bool Queue::dequeue(Item & item)
{
    if (isempty())
        return false;
    item = front->item;
    Node * temp;
    temp=front;              // is it necessary
    front = front->next;
    items--;
    delete temp;
    if (items == 0)
        rear = NULL;   //why it is not front=rear=Null ;
    return true;
}

2 个答案:

答案 0 :(得分:0)

temp = front;

保存指向front元素的指针,以便在修改front后将其删除。

如果队列为空,front = front->next;已将front设置为空,则无需再次执行此操作。

答案 1 :(得分:0)

此队列中的节点存储为指针。要实际创建节点,某些代码(如Node* tmp = new Node())可能位于enqueue-Function中。

使用front = front->next;,指向第一个元素的指针将移动到队列中的下一个元素。但是之前的front - 节点呢?通过移动指针我们“忘记”它的地址,但我们不删除对象或释放内存。我们必须使用delete来执行此操作,这就是临时存储地址以调用删除的原因。不删除它会导致内存泄漏。

关于第二个问题:front指针已移至front->next。如果队列中只有一个元素,那该怎么办?可能NULLenqueue - 函数应该确保NULL。 (“注意:如果您要管理此代码,最好将nullptr替换为rear)。 唯一尚未更新的变量是$(document).ready(function() { $("#bar").animate({ width: '0%' }, 3000); });