我需要为链表队列实现一个 toString() 递归方法。我知道我的 toString 方法在我上周做的一个链表实现上运行良好,所以我处理它的队列方面的方式有问题。
我的 QueueList 的 toString 方法:
public String toString()
{
if (front.info == null)
{
System.out.println("Error, queue is empty");
return "";
}
if (front.link == null) //base case: if this is last element in stack
{
return (" \"" + front.info + "\" , ");
}
else //normal recursive function
{
return (" \"" + front.info + "\" , " + front.link.toString());
}
}
和我的构造函数等队列列表:
public class QueueNode
{
E info;
QueueNode link;
}
private QueueNode front;//first element to be placed into queue
private QueueNode rear;//last element to be placed into queue
private int NoE;//counter for number of elements in queue
public QueueList()
{
front = null;
rear = null;
NoE = 0;
}
我试图用这个测试看看它发生了什么:
public boolean test() {
QueueList<String> q = new QueueList<String>();
q.enqueue("The Godfather");
q.enqueue("Casino");
q.enqueue("Goodfellas");
String r = q.toString();
q.PrettyPrint();
与输出
IN -> [ "The Godfather" , QueueList$QueueNode@a3901c6] -> OUT.
我意识到这是因为我front.link.toString()
在方法的递归部分中说toString
,但即使我将其更改为front.link.info.toString()
,我的输出也是
IN -> [ "The Godfather" , Casino] -> OUT.
这可能与我的入队和出队方法有关,如下所示:
public void enqueue(E element)
{
QueueNode newNode = new QueueNode();//creates new Node to hold element
newNode.info = element;//set info of new Node to element
newNode.link = null;//make link null since it's at back of list
if (rear == null)//checks if queue is empty
{
front = newNode;
}
else
{
rear.link = newNode;//sets second to last node's link to newNode
}
rear = newNode;//makes newNode the new last link
NoE++;//increase counter
}
public E dequeue() throws InvalidOperationException
{
if (front == null)//sanitize code
{
throw new InvalidOperationException("There is nothing in the queue.");
}
E element = front.info;//creates an element file that takes the info in front of queue
front = front.link;//makes second-to-front element new front
if (front == null)//if this emptied the queue, make sure rear is also empty
{
rear = null;
}
NoE--;//reduce counter
return element;
}
如果可以的话,请帮助我。谢谢。