【问题标题】:Circular Queue Array循环队列数组
【发布时间】:2023-03-07 14:35:01
【问题描述】:

大家好,我正在尝试实现一个循环数组,但有些事情并不完全正确。我不确定是否在 add 方法或显示中。当您运行调试器时,数字在那里,但我无法按顺序排列它们。请你看看并给我一个反馈。谢谢。

public static void main (String[] args)
{
    Scanner input = new Scanner (System.in);
    Queue q1 = new Queue();
    int choice = 0;

    do
    {
        System.out.println ("Menu:");
        System.out.println ("1: Add");
        System.out.println ("2: Remove");
        System.out.println ("3: Display");
        System.out.println ("4: Exit");

        System.out.print ("\nChoice: ");
        choice = input.nextInt ();

        switch ( choice )
        {
            case 1:
                System.out.print ("\nEnter a number: ");
                int num = input.nextInt ();
                q1.add (num);
                break;
            case 2:
                q1.remove ();
                break;
            case 3:
                q1.display ();
                break;
            case 4:
                System.out.println ("Good Bye");
                break;
            default:
                System.out.println ("Wrong choice!");
                break;
        }

    } while ( choice != 4 );


}

}

公共类队列 {

private final int SIZE;
private int first;
private int last;
private int[] q;

public Queue ()
{
    SIZE = 5;
    q = new int[ SIZE ];
    first = 0;
    last = 0;
}

public boolean isFull ()
{
    return last == SIZE;
}

public boolean isEmpty ()
{
    return last == first;
}

public void add (int x)
{
    if (  ! isFull () )
    {
        q[ ( first + last ) % q.length ] = x;
        last ++;
    } else
    {
        System.out.println ("\nThe queue is full!");
    }
}

int remove ()
{
    int x = 0;
    if (  ! isEmpty () )
    {
        x = q[ first ];
        first = ( first + 1 ) % q.length;
        last --;
    } else
    {
        System.out.println ("The queue is empy");
    }
    return x;

}

public void display ()
{
    if (  ! isEmpty () )
    {
        for ( int i = first; i < SIZE; i ++ )
        {
            System.out.println (q[ i ]);
        }


    } else
    {
        System.out.println ("The queue is emptry");
    }
}

【问题讨论】:

  • 欢迎来到 Stack Overflow!寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误重现它所需的最短代码在问题本身。没有明确问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable example

标签: java arrays queue


【解决方案1】:

效果很好。你能更具体地说明你的错误吗?

【讨论】:

  • 如果您输入:1,2,3,4,5 然后删除 1 和 2 让我们说。然后你要显示,你会得到3,4,5。假设您想添加 6 和 7,但您将无法看到它们。所以如果你显示,你仍然会得到 3,4,5。不知何故,我需要让 6 和 7 从队列后面可见
【解决方案2】:

add() 应该只更新last。 remove() 应该只更新first。 add() 需要防止队列变满,或者代码需要使用队列中的元素计数来检查队列是否已满(相对于空,因为 last == first 如果为空或已满),其中case add() 需要防止队列溢出。 add() 可以返回一个代码来指示 add() 是成功(没有溢出)还是失败(溢出)。 add() 可以选择返回第三个代码值,以指示队列先前为空,以防队列从空变为非空时需要一些特殊操作。

【讨论】:

  • 谢谢,我会试试看的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-10
  • 1970-01-01
  • 1970-01-01
  • 2012-01-30
相关资源
最近更新 更多