我应该从伪代码中实现一个入队算法。但是,每当我输入任何内容时,排队都会保持为空。

队列类

    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/

10-11 09:13