gpt4 book ai didi

java - 如何仅使用后部外部指针使这个链接队列循环?

转载 作者:行者123 更新时间:2023-11-30 05:08:14 26 4
gpt4 key购买 nike

public void enqueue(Object element)
// Adds element to the rear of this queue.
{
LLObjectNode newNode = new LLObjectNode(element);
if (rear == null)
front = newNode;
else
rear.setLink(newNode);
rear = newNode;
}

public Object dequeue()
// Throws QueueUnderflowException if this queue is empty;
// otherwise, removes front element from this queue and returns it.
{
if (isEmpty())
throw new QueueUnderflowException("Dequeue attempted on empty queue.");
else
{
Object element;
element = front.getInfo();
front = front.getLink();
if (front == null)
rear = null;

return element;
}
}

public boolean isEmpty()
// Returns true if this queue is empty; otherwise, returns false.
{
if (front == null)
return true;
else
return false;
}

最佳答案

public class CircLinkedUnbndQueue<T> implements UnboundedQueueInterface<T>
{
protected LLNode<T> rear; // reference to the rear of this queue

public CircLinkedUnbndQueue()
{
rear = null;
}

public void enqueue(T element)
// Adds element to the rear of this queue.
{
LLNode<T> newNode = new LLNode<T>(element);

if (rear == null)
{
rear = newNode;
}
else
{
//links the newNode to the rear node's pointer and then 're'points the
//rear node to the newNode.
if(rear.getLink() == null)
{
rear.setLink(newNode);
newNode.setLink(rear);
}
else
{
newNode.setLink(rear.getLink());
rear.setLink(newNode);
}
}
//'repositions' the reat node at the end of the queue.
rear = newNode;
}

public T dequeue()
// Throws QueueUnderflowException if this queue is empty;
// otherwise, removes front element from this queue and returns it.
{
if (isEmpty())
throw new QueueUnderflowException("Dequeue attempted on empty queue.");
else
{
T element;

rear = rear.getLink();
element = rear.getInfo();

if (rear.getLink() == null)
rear = null;

return element;
}
}

public boolean isEmpty()
// Returns true if this queue is empty; otherwise, returns false.
{
if (rear == null)
return true;
else
return false;
}
}

我知道这是一篇旧帖子,但我最近遇到了这个问题,并且相信这更符合所提出的问题,因为它仅使用后节点。

关于java - 如何仅使用后部外部指针使这个链接队列循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4357798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com