循环链接列表用于表示队列。单个变量p用于访问队列。 p指向哪个节点,以便enQueue和deQueue操作都可以在恒定时间内执行? (GATE 2004)
(A)后节点
(B)前节点
(C)用单个指针不可能
(D)节点在前面答案: (A)
说明:答案不是“(b)前节点”,因为我们无法在O(1)中从前向后获取,但是如果p在后方,我们可以在O(1)中实现enQueue和deQueue,因为从后方我们可以获取在O(1)中的前面。以下是示例函数。请注意,这些功能只是示例无法正常工作。缺少用于处理基本情况的代码。
/* p is pointer to address of rear (double pointer). This function adds new
node after rear and updates rear which is *p to point to new node */
void enQueue(struct node **p, struct node *new_node)
{
/* Missing code to handle base cases like *p is NULL */
new_node->next = (*p)->next;
(*p)->next = new_node;
(*p) = new_node /* new is now rear */
/* Note that p->next is again front and p is rear */
}
/* p is pointer to rear. This function removes the front element and
returns the dequeued element from the queue */
struct node *deQueue(struct node *p)
{
/* Missing code to handle base cases like p is NULL,
p->next is NULL,... etc */
struct node *temp = p->next;
p->next = p->next->next;
return temp;
/* Note that p->next is again front and p is rear */
}
这个问题的测验
这个问题的测验