gpt4 book ai didi

java - 队列不断返回空

转载 作者:行者123 更新时间:2023-12-01 12:39:34 25 4
gpt4 key购买 nike

有一个排队算法,我应该用伪代码来实现。但是,每当我输入任何内容时,队列都会返回空。

队列类

    public class Queue
{
Node head;
int size;
Node tail;
public Queue()
{
head = null;
tail = head;
size = 0;
}
public int size()
{
return size;
}
public void enqueue(Node elem)
{
Node node = null;
node = elem;
node.setNext(null);


if (size == 0)
{
System.out.println("Queue is empty ");
head = node;
}
else
{
tail.setNext(node);
tail = node;
size++;
}
}

public int dequeue()
{
int tmp = 0;
if (size == 0)
{
System.out.println("Queue is empty.");
}
else
{
tmp = head.getPrice();
head = head.getNext();
size--;
}
if (size == 0)
{
tail = null;

}
return tmp;
}

}

测试者类别

import java.util.Scanner;
public class Test {

public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int amount;
String buysell;
int shares;

Queue q = new Queue();

System.out.println("Enter: buy x(shares amount) x(buy amount) or sell x(shares amount) x(sell amount)");

while(in.hasNext())
{

buysell = in.next();
shares = in.nextInt();
amount = in.nextInt();

if(buysell.compareTo("buy") == 0)
{

q.enqueue(new Node(shares, amount, null));
System.out.println("Enqueing");
}
else
{
q.dequeue();
System.out.println("Dequeing");
}

}



}
}

节点类

public class Node
{
private int shares;
private int price;
private Node next;
private int size;
public Node(int ashares,int aprice, Node n)
{
shares = ashares;
price = aprice;
next = n;

}
public int getPrice()
{
return price;
}

public Node getNext()
{
return next;
}

public void setPrice(int el)
{
price = el;
}

public int getShares()
{
return shares;
}

public void setShares(int el)
{
shares = el;
}
public void setNext(Node n)
{
next = n;

}

}

我知道大小没有增加,所以它似乎陷入了条件语句中,任何帮助我朝正确方向前进的帮助都会很棒,谢谢。

最佳答案

if (size == 0)
{
System.out.println("Queue is empty ");
head = node;
}

插入第一个节点时不会增加大小。因此,当尝试插入下一个时,大小仍然 = 0,因此您只需更换头部。

只需将 size++ 放在 IF 语句之外(之后),它就应该按您的预期工作。

我刚刚看到,尾部和头部还有另一个问题。所以 if 子句应该是:

if (size == 0)
{
System.out.println("Queue is empty ");
head = node;
tail = head;
}
else
{
// your code here
}
size++;

关于java - 队列不断返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25244976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com