【问题标题】:Comparing the front elements of a queue using the >= operator使用 >= 运算符比较队列的前面元素
【发布时间】:2015-01-25 21:41:59
【问题描述】:

这是一个典型的堆栈排列,借助 2 个队列,一个用于输入,另一个用于输出。我想检查 q2 (输出)是否是 q1 (输入)的正确排列,但我无法比较 2 个队列的前选择,因为它们的类型为 Object,因为 >= 运算符将不起作用它。

package a2;
import a1queue.*;
import a1stack.*;

public class Permu {

    public static int stperm(ArrayQueue q1,ArrayQueue q2) throws EmptyStackException, QueueFullException, EmptyQueueException, StackFullException{

    ArrayStack s = new ArrayStack();


    while(!q2.isEmpty()){
        while(!q1.isEmpty() && q2.front() >=q1.front() ){// shows error here

            if(q2.front() == q1.front()){
                System.out.println("enqueue(q2,dequeue(q1))-> "+ q1.front() + " is enqueued in q2.");
                q1.dequeue();
                q2.dequeue();
                                        }

            else {
                System.out.println("push(s,dequeue(q1)) -> " + q1.front() + " is pushed into stack.");
                s.push(q1.dequeue());

                }


        }
        if (q2.front() == s.top()){
            System.out.println("enqueue(q2, pop(s)) "+s.top() +" is popped from stack & enqueued in q2.");
            s.pop();
            q2.dequeue();

        }
        else{
            q1.enqueue(s.pop());
            System.out.println(s.top());
            break;


            }


    }
    System.out.println("it is a permutation");
    return 0;


}



private static int compare(java.lang.Object front, java.lang.Object front2) {
    // TODO Auto-generated method stub
    return 0;
}



private static int Object(Object front) {
    // TODO Auto-generated method stub
    return 0;
}



public static void main(String[] args) throws QueueFullException,StackFullException,EmptyQueueException,EmptyStackException {


     ArrayQueue q1 = new ArrayQueue();
     ArrayQueue q2 = new ArrayQueue();


    q1.enqueue(1);
    q1.enqueue(2);
    q1.enqueue(3);
    q1.enqueue(4);
    q1.enqueue(5);
    q1.enqueue(6);

    q2.enqueue(4);
    q2.enqueue(5);
    q2.enqueue(3);
    q2.enqueue(2);
    q2.enqueue(1);
    q2.enqueue(6);

    System.out.print( stperm(q1,q2));
}
}

【问题讨论】:

  • 为什么不让队列通用呢?我看到您正在添加整数,因此 Queue 将返回一个您可以比较的整数。

标签: java queue operators


【解决方案1】:

你需要创建你的对象Comparable

public class Obj implements Comparable<Obj>
{
...
}

然后指定要比较的属性。关于您想要比较您的对象的内容?根据他们的身份证?根据他们的名字?

请注意,您不能在 Java 中使用运算符进行比较。您应该调用应该在 Comparable 对象中定义的 compareTo() 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 2017-03-28
    相关资源
    最近更新 更多