带链表的队列是如何工作的
How Queue with Linked List Works
有人可以向我解释一下 enqueue
方法的工作原理吗?
我想知道在重新分配后部时如何更新前部?
public class Queue {
public QNode front, rear;
public Queue()
{
this.front = null;
this.rear = null;
}
public void enqueue(int key)
{
QNode temp = new QNode(key);
if (this.rear == null) {
this.rear = temp;
this.front = temp;
return;
}
this.rear.next = temp;
this.rear = temp;
}
public void dequeue()
{
if (this.front == null)
return;
QNode temp = this.front;
this.front = this.front.next;
if (this.front == null)
this.rear = null;
}
}
首先,该方法使用给定的键创建一个新节点,然后检查 rear 是否为空(这实际上意味着队列为空)。如果队列为空,它会将带有键的新节点设置为后部和前部,因为它是列表中唯一的节点。如果列表不为空,它将节点链接到后方 (this.rear.next==temp
) 并将其更新为新的后方。
关于你前面的问题,使用enqueue时不需要更新。 Enqueue 在链表的末尾添加一个节点,并将其更新为尾部。 Dequeue从前端移除一个节点并更新新的前端(原前端之后的那个)。
有人可以向我解释一下 enqueue
方法的工作原理吗?
我想知道在重新分配后部时如何更新前部?
public class Queue { public QNode front, rear; public Queue() { this.front = null; this.rear = null; } public void enqueue(int key) { QNode temp = new QNode(key); if (this.rear == null) { this.rear = temp; this.front = temp; return; } this.rear.next = temp; this.rear = temp; } public void dequeue() { if (this.front == null) return; QNode temp = this.front; this.front = this.front.next; if (this.front == null) this.rear = null; }
}
首先,该方法使用给定的键创建一个新节点,然后检查 rear 是否为空(这实际上意味着队列为空)。如果队列为空,它会将带有键的新节点设置为后部和前部,因为它是列表中唯一的节点。如果列表不为空,它将节点链接到后方 (this.rear.next==temp
) 并将其更新为新的后方。
关于你前面的问题,使用enqueue时不需要更新。 Enqueue 在链表的末尾添加一个节点,并将其更新为尾部。 Dequeue从前端移除一个节点并更新新的前端(原前端之后的那个)。