上体育课的时候,老师已经把班级同学排成了两个队列,而且每个队列都是按照从底到高排好队,现在需要把两个队列合并,合并后需要保证还是从低到高排列。合并队列,你能编程实现吗?
时间: 2024-03-02 07:51:15 浏览: 60
当然可以,可以使用双指针的方法实现。具体的代码实现如下:
```c++
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<int> q1, q2;
q1.push(1);
q1.push(3);
q1.push(5);
q2.push(2);
q2.push(4);
q2.push(6);
queue<int> q3;
while (!q1.empty() && !q2.empty()) {
if (q1.front() <= q2.front()) {
q3.push(q1.front());
q1.pop();
} else {
q3.push(q2.front());
q2.pop();
}
}
while (!q1.empty()) {
q3.push(q1.front());
q1.pop();
}
while (!q2.empty()) {
q3.push(q2.front());
q2.pop();
}
while (!q3.empty()) {
cout << q3.front() << " ";
q3.pop();
}
return 0;
}
```
这个程序中,我们定义了三个队列,分别存储两个初始队列的元素和合并后新队列的元素。我们使用了双指针的方法,分别从两个初始队列中取出当前最小的元素进行比较,将较小的元素加入到新队列中。当其中一个队列为空时,我们将剩余的元素全部加入到新队列中。最后,我们依次输出新队列中的元素,即为合并后的结果。