我想我的queue类有问题,因为我知道使用队列使用fifo方法,但是我想确保在添加元素时它被添加到队列的末尾。在我的主程序中,我添加了数字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;
}
3条答案
按热度按时间l2osamch1#
一个更简单的方法是引入一个尾部和一个头部,使您的队列成为双端的,无需每次添加一个项时遍历整个队列。
确实应该调用该方法
add
因为它是附加到结尾而不是插入。eufgjt7s2#
在代码中修复(改为字符串方法printlist):
rfbsl7qr3#
你的逻辑
insert()
方法需要注意。我已经修改了else
该方法的一部分如下所示,并且起到了作用:以下是全体工人阶级: