[英]Java - I was modifying a stack linked list into a queue linked list but my dequeue method still behaves like pop
private Node back
还没有被使用,并且enqueue
(推送)和dequeue
(pop是)除了重命名一些东西之外还没有真正被修改过。 同样,这最初是一个堆栈,但我正在尝试将其修改为队列。 我在使用int
之前已经完成了非链接列表队列和堆栈,但是对于对象和链接列表,我有点迷失。
public class DogQueue
{
private Node front = null;
private Node back = null;
private Node element = null;
private int counter = 0;
以上只是设置变量。
private class Node //This sets up the Linked List
//Data Structure with nodes.
{
private Dog doggy;
private Node nextNode;
private Node firstNode;
Node(Dog newDog)
{
doggy = newDog;
}
}
我不太了解的节点内容是上面的。
public void enqueue(Dog aDog) //This should enqueue
//an object of type Dog.
{
Node dogNode = new Node(aDog);
dogNode.nextNode = front;
counter++;
front = dogNode;
}
上面这里没有修改push方法,只是重命名。
public Dog dequeue() //This should output
//the first entry in the list.
{
Dog firstDog = front.doggy;
element = front.firstNode;
counter--;
return firstDog;
}
上面这里是我最麻烦的地方 - 目前它的行为类似于pop(获取和删除列表中最后输入的元素)。
public boolean isFull() //Checks to see if List is Full.
{
return ( counter == 5 );
}
我将计数器设置为最多5,所以我可以调试isFull。
public boolean isEmpty() //Checks to see if List is empty
{
if ( counter == 0 )
{
return true;
} else {
return false;
}
}
这只是说如果counter为零,则isEmpty为true(否则为false)。
}
我吮吸数据结构,但我相信你的入队和出队仍然像pop和push一样。 前面应指向队列的头部,尾部指向最后一个有效对象。 所以尾巴应该最终指向null ..我认为它应该是这样的:
public void enqueue(Dog aDog)
{
Node dogNode = new Node(aDog);
counter++;
if (front == null)
front = back = dogNode;
else
{
back.nextNode = dogNode;
back = dogNode;
}
}
public Node dequeue()
{
if(front == null) return null;
Dog firstDog = front ;
front = front.nextNode;
counter--;
return firstDog;
}
这是主要问题。 队列是FIFO(先进先出),堆栈是LIFO(后进先出)。 对于队列,您排队的第一个元素是您收到的第一个元素,并且您推入堆栈的最新元素是您收到的第一个元素。
为此,让我们稍微检查一下你的代码。
public void enqueue(Dog aDog) { //This should enqueue an object of type Dog.
Node dogNode = new Node(aDog);
dogNode.nextNode = front;
counter++;
front = dogNode;
}
您将新狗元素的下一个节点设置在前面。 您必须转到队列的末尾,将最近的节点设置为新节点,并将新节点设置为null。 使用您的代码,它看起来像这样:
public void enqueue(Dog aDog) {
if(front == null) {
front = new Node(aDog);
back = front; // back will move later
} else {
Node tmp = new Node(aDog);
tmp.setFirstNode(back);
back.setNextNode(tmp);
back = tmp;
}
}
public Dog dequeue() { //This should output the first entry in the list.
Dog firstDog = front.doggy;
element = front.firstNode;
counter--;
return firstDog;
}
至少,这确实显示了队列中的第一件事。 但它实际上并没有移动头指针! 使用您的代码,为此,它看起来像这样:
public Dog dequeue() {
if(head == null) {
return null;
} else {
Dog tmp = front.getDoggy()
front = front.getNextNode(); //move the front to point to the next location
front.getFirstNode().setNextNode(null); //sever the link to the first element
front.setFirstNode(null); //sever the link to the first element
return tmp;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.