我在使用c++的链表实现队列的入队和出队时遇到了一些麻烦。我的老师说模板是不可行的,我不能改变他给我们的公共(public)和私有(private)职能。我不断遇到细分错误。我不太了解自己在做什么错。我已经包括了头文件以及入队和出队功能。
header
const int MAX_STRING = 6;
typedef char Element300[MAX_STRING + 1];
class Queue300
{
public:
Queue300();
Queue300(Queue300&);
~Queue300();
void enQueue300(const Element300);
void deQueue300(Element300);
void view300();
private:
struct Node300;
typedef Node300 * NodePtr300;
struct Node300
{
Element300 element;
NodePtr300 next;
};
NodePtr300 front, rear;
};
排队
void Queue300::enQueue300(const Element300 input)
{
NodePtr300 temp = NULL;
temp = new (std::nothrow) Node300;
if (temp == NULL)
{
cerr << "The queue is full, could not add(enqueue) any more elements." << endl;
}
else if (front == NULL && rear == NULL)
{
strcpy(temp->element, input);
rear = temp;
rear->next = NULL;
front = rear;
temp = NULL;
}
else
{
strcpy(temp->element, input);
temp = rear->next;
rear = temp;
rear->next = NULL;
temp = NULL;
}
}
出队
void Queue300::deQueue300(Element300 input)
{
NodePtr300 temp = NULL;
if (rear == NULL && front == NULL)
{
cerr << "The queue is already empty, could not delete(dequeue) any more elements." << endl;
}
else if (front == rear)
{
strcpy(temp->element, input);
temp = front;
delete temp;
temp = NULL;
front = NULL;
rear = NULL;
}
else
{
strcpy(temp->element, input);
temp = front;
front = front->next;
temp->next = NULL;
delete temp;
temp = NULL;
}
}
最佳答案
让我们看一下入队:
if (temp == NULL)
{
...
}
else if (front == NULL && rear == NULL)
{
...
}
else
{
strcpy(temp->element, input); // copy input into temp->element
// temp points to rear->next (it is always NULL, isn't it?)
// we lost the Node300 previously pointed by temp.
temp = rear->next;
// rear points to the same location as temp (NULL)
rear = temp;
// rear->next: dereferencing NULL /!\
rear->next = NULL;
temp = NULL;
}
ASCII艺术的时间。这是入队之前:
REAR -------------------
|
v
[0]--> ... -->[N]-->NULL
^
FRONT ---|
您分配一个
[X]
引用的节点temp
:temp --> [X]
REAR的下一个必须指向同一节点:
REAR
|
v
[N] --> [X]
^
|
temp
然后,必须更新REAR以引用
[X]
。就指针操作而言,您甚至不需要
temp
指针,但让我们保留它,因为您正在检查节点是否之前已正确分配,这很高兴。rear->next = temp;
rear = temp; // or rear = rear->next;
temp->next = NULL; // or rear->next = NULL;
还要注意,您在两个
strcpy(temp->element, input);
分支中都执行else
。您可以在temp == NULL
时从函数返回,并在检查front
和rear
是否均为NULL之前进行复制。