我正在尝试使用单个引用实现循环链接列表队列。我相信它是基于测试的FIFO(后面是每次元素入队时都应该更新),但它是反向打印。我应该期待这个,还是我错过了什么?我试过更改toString()。这是我的CircularLinkedQueue类:
public class CircularLinkedQueue implements UnboundedQueueInterface
{
protected LLObjectNode rear;
public CircularLinkedQueue()
{
rear = null;
}
public void enqueue(Object element)
{
LLObjectNode newNode = new LLObjectNode(element);
if (rear == null)
newNode.setLink(newNode);
newNode.setLink(rear);
rear = newNode;
}// end enqueue()
public Object dequeue() throws QueueUnderflowException
{
if (isEmpty())
throw new QueueUnderflowException("Dequeue attempted on an empty queue.");
else
{
Object element; // create a reference to the Object to return
element = rear.getLink(); // set the reference to the information in the front node
rear = rear.getLink(); // set the rear reference to point at the next node
return element;
}// end else
}// end dequeue()
public boolean isEmpty()
{
return (rear == null);
}// end isEmpty()
// *** Exercise #25b *** works
public Object front()
// returns a reference to the front element on the queue.
// precondition: queue is not empty.
{
Object frontObj;
frontObj = rear.getLink();
return frontObj;
}// end front()
public int size()
{
LLObjectNode node;
node = rear;
int count = 0;
while (node != null)
{
count++;
node = node.getLink();
}
return count;
}// end size()
public String toString()
{
String circleQStr = "";
LLObjectNode node;
int count = 0;
node = rear;
while (node != null)
{
count++;
circleQStr = circleQStr + count + ". " + node.getInfo() + "\n";
node = node.getLink();
}// end while
return circleQStr;
}// end toString()
}// end class CircularLinkedQueue
以下是getLink()
和setLink()
:
public void setLink(LLObjectNode link)
{
// sets link of this LLObjectNode
this.link = link;
}
public LLObjectNode getLink()
{
// returns link of this LLObjectNode
return link;
}
感谢您阅读我的帖子。
答案 0 :(得分:3)
此代码存在许多问题,我认为这与您说明的问题无关,但如果您的起始节点位于后方,则需要在打印之前前进,否则它将首先打印后部。另外......我认为你的size()
函数不会返回...在循环队列中,下一个元素永远不会为空。如果没有发布getLink()
和setLink()
修改好吧,我认为问题是你的enequeue
方法应该是这样的
public void enqueue(Object element)
{
LLObjectNode newNode = new LLObjectNode(element);
if (rear == null){
newNode.setLink(newNode);
}else{
newNode.setLink(rear.getLink());
rear.setLink(newNode);
}
rear = newNode;
}// end enqueue()
此外,您需要更改出队方法。现在你的后部指向你刚刚出局的元素。
public Object dequeue() throws QueueUnderflowException
{
if (isEmpty())
throw new QueueUnderflowException("Dequeue attempted on an empty queue.");
else
{
Object element; // create a reference to the Object to return
element = rear.getLink(); // set the reference to the information in the front node
rear.setLink(element.getLink()); // set the rear reference to point at the next node
return element;
}// end else
}// end dequeue()