【发布时间】:2021-03-15 12:18:41
【问题描述】:
我认为我的 Queue 类有问题,因为我知道使用 Queue 会使用 FIFO 方法,但我想确保当我添加一个元素时,它会添加到 Queue 的末尾。在我的主程序中,我添加了数字 1-4,但是当我想使用 Queue 类中的 toString 方法打印整个队列时,它只会打印出第一个元素 1。我将不胜感激!
谢谢!
public class QuestionFive
{
public static void main(String[] args)
{
// creating a queue
Queue q = new Queue();
// adding numbers 1,2,3 and 4
q.insert(1);
q.insert(2);
q.insert(3);
q.insert(4);
System.out.println(q);
}
}
class Queue
{
//Private Data Member
private Link _head;
//Constructor: A constructor to create an empty Queue,
public Queue()
{
_head = null;
}
//Insert Method: A method to insert a given Object into the Queue.
//Note: We will inserton
public void insert(Object item)
{
Link add = new Link();
add.data = item;
add.next = null;
if(_head == null)
{
_head = add;
}
else
{
for(Link curr = _head; curr.next != null; curr = curr.next)
{
curr.next = add;
}
}
}
//Delete Method: A method to delete an Object from the Queue
public Object delete()
{
if ( _head == null ) return null;
Link prev = null;
Link curr = _head;
while (curr.next != null )
{
prev = curr;
curr = curr.next;
}
if ( prev != null )
{
prev.next = null;
}
else
{
_head = null;
}
return curr.data;
}
// IsEmpty Method: A method to test for an empty Queue
public boolean isEmpty()
{
// queue is empty if front is null
return (_head == null);
}
//toString Method:
public String toString()
{
String s = "";
for (Link curr = _head; curr != null; curr = curr.next)
{
s = s + " " + curr.data;
}
return s;
}
}
//Link Class
class Link
{
public Object data;
public Link next;
}
【问题讨论】:
-
您是否尝试过使用调试器和/或在将项目添加到队列时记录代码的行为?在我看来,您的
insert方法实际上是在每次添加内容时重新编写队列,因此您最终只得到_head条目。 -
curr.next = add;属于循环之后,而不是循环内部。 -
@KevinAnderson 如果 curr.next = add 在循环之外,它不会工作吗?
-
它不会,除非你在循环之前声明
curr并将循环写为for (curr = _head;...。我们的想法是让循环将curr一直移动到最后一个节点,然后让curr仍然可用,这样你就可以将新节点放在末尾next = add;,
标签: java linked-list queue tostring implementation