1
我想实现一个单引用的循环链表队列。我相信这是基于测试的先进先出(每次元素入队后都会更新),但是它是反向打印的。我应该期待这一点,还是我错过了一些东西?我试过改变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;
}
感谢您阅读我的文章。
size()实际上有效。我编辑添加'getLink()'和'setLink()'。当我对'toString()'进行破解时,我得到'NullPointerException'或者它不打印最后一个元素。 – 2011-04-13 02:55:49
@nerdess,嗯,它不应该。你不应该在循环队列中有一个'null' nextItem指针。看到我上面的编辑,让我知道,如果这有帮助。 – 2011-04-13 03:06:35
@nerdess,另请参阅我的编辑到您的出队方法。当你出队时,因为它出现在列表的前面,所以你不想修改'后部'元素,只是它指向的内容。 – 2011-04-13 03:10:47