《算法4》2.2.14题解

浏览:55 发布日期:2025-05-07 16:47:17

归并有序队列

这个题比较简单,参考前面的merge方法:

private static Queue<Integer> merge(Queue<Integer> a, Queue<Integer> b)
{
    Queue<Integer> q = new Queue<>();
    while (!a.isEmpty() || !b.isEmpty())
    {
        if (a.isEmpty())
        {
            while (!b.isEmpty())
            {
                q.enqueue(b.dequeue());
            }
        }
        else if (b.isEmpty())
        {
            while (!a.isEmpty())
            {
                q.enqueue(a.dequeue());
            }
        }
        else // 都不为空
        {
            int a1 = a.peek();
            int b1 = b.peek();
            if (a1 <= b1)
            {
                q.enqueue(a.dequeue());
            }
            else // a1 > b1
            {
                q.enqueue(b.dequeue());
            }
        }
    }

    return q;
}

public static void main(String[] args)
{
    Queue<Integer> q1 = new Queue<>();
    q1.enqueue(3);
    q1.enqueue(8);
    q1.enqueue(9);
    q1.enqueue(10);

    Queue<Integer> q2 = new Queue<>();
    q2.enqueue(2);
    q2.enqueue(3);
    q2.enqueue(5);
    q2.enqueue(6);

    show(q1);
    show(q2);

    var q = merge(q1, q2);
    show(q);
}

执行输出结果为:

3 8 9 10 
2 3 5 6 
2 3 3 5 6 8 9 10