private ArrayQueue<E> merge( ArrayQueue<E> q1, ArrayQueue<E> q2 ) throws ArrayQueueException
{
ArrayQueue<E> mergeQueue = new ArrayQueue<E>( q1.size() + q2.size() );
ArrayQueue<E> smallestQueue = smallestQueue( q1, q2 );
ArrayQueue<E> biggestQueue = biggestQueue( q1, q2 );
for ( int index = 0; index < smallestQueue.size(); index++ )
{
E elementOne = smallestQueue.dequeue();
E elementTwo = biggestQueue.dequeue();
if ( elementOne.compareTo( elementTwo ) < 0 )
{
mergeQueue.enqueue( elementOne );
mergeQueue.enqueue( elementTwo );
}
else
{
mergeQueue.enqueue( elementTwo );
mergeQueue.enqueue( elementOne );
}
}
for ( int index = 0; index < biggestQueue.size(); index++ )
{
mergeQueue.enqueue( biggestQueue.dequeue() );
}
return ( mergeQueue );
}
我一直在进行一项涉及创建合并两个队列的方法的练习。当两个队列的大小相同时,我的上述尝试就会起作用,否则会出错。
实现这一目标的最佳方式是什么?
感谢。
答案 0 :(得分:1)
这不是你方法的唯一问题。
正确方法的伪代码如下所示:
while (both queues are not empty) {
retrieve first elements without removing them from their queues
compare them
put the appropriate element into the new queue and remove it from its old queue
}
if any of old queues is not empty, put its elements into the new queue