为什么要使用双指针来创建队列

why is a double pointer being used to create a Queue?

本文关键字:创建 队列 指针 为什么      更新时间:2024-05-10

我有两个类Node和Queue。在Queue构造函数中,我们需要在堆中创建一个Node类型的数组。我的问题是,为什么我们应该使用双指针Node **Q,然后像这样创建一个数组Q=new Node*[size],而我们本可以用一个指针创建一个节点数组?如Node *QQ = new Node[size]

class Node
{
public:
Node *lchild;
int data;
Node *rchild;
};
class Queue {
private:
int front;
int rear;
int size;
Node **Q;
public:
Queue(){front=rear=-1;size=10;Q=new Node*[size];}
Queue(int size){front=rear=-1;this->size=size;;Q=new
Node*[size];}
void enqueue(Node *x);
Node *dequeue();
int isEmpty(){ return front==rear;}
};

首先,让我们明确一下,我们正在研究两种不同的数据结构:

  1. 一个由Node对象定义的二叉树
  2. 由固定大小缓冲区(可能是环形缓冲区(支持的队列

还有一种算法使用这些数据结构。基于其中一个注释,该算法从排队的节点构建一个二叉树。换句话说,该算法希望修改原始Node对象,而不希望修改它们的副本。

因此,分配Node *数组的原因是队列不必复制Node对象。相反,入队的指针与后来出队的指针完全相同。这允许链接算法对原始节点进行操作,并因此具有所需的效果。