enqueue一直空着

时间:2014-08-11 13:53:33

标签: java queue

我应该从伪代码实现一个入队算法。但是,每当我输入任何enqueue时,都会返回空。

QUEUE CLASS

    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;
} 

}

TESTER CLASS

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");
            }

        }



    }
}

NODE CLASS

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;

  }

}

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

1 个答案:

答案 0 :(得分:1)

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++;