两个栈表示一个队列代码c++
时间: 2023-12-24 21:23:42 浏览: 28
以下是用两个栈实现一个队列的C++代码:
```
class CQueue {
std::stack<int> s1; //入
std::stack<int> s2; //出
public:
CQueue() {}
void appendTail(int value) {
s1.push(value);
}
int deleteHead() {
int val;
if (s2.empty()) {
if (s1.empty()) {
return -1;
}
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
val = s2.top();
s2.pop();
return val;
}
};
```
相关问题
用两个队列实现一个栈 c++
可以用两个队列来模拟一个栈的数据结构,具体实现如下:
1. 定义两个队列queue1和queue2;
2. 将元素压入栈时,将元素放入queue1中;
3. 将元素弹出栈时,先将queue1中的元素依次出队并放入queue2中,直到queue1中只剩一个元素,将该元素出队返回即可;
4. 在弹出元素时,如果queue1中只有一个元素,直接出队返回即可,不需要将元素放入queue2中;
5. 在弹出元素时,交换queue1和queue2的指针,使得下一次弹出时可以从另一个队列中取出元素;
6. 使用两个队列实现的栈,其空间复杂度为O(n),其中n为栈中元素的个数。
以下是使用C语言实现的代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Queue {
int* data;
int front;
int rear;
} Queue;
typedef struct Stack {
Queue* queue1;
Queue* queue2;
} Stack;
Queue* createQueue(int size) {
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->data = (int*)malloc(sizeof(int) * size);
queue->front = 0;
queue->rear = 0;
return queue;
}
Stack* createStack(int size) {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->queue1 = createQueue(size);
stack->queue2 = createQueue(size);
return stack;
}
void push(Stack* stack, int value) {
stack->queue1->data[stack->queue1->rear] = value;
stack->queue1->rear++;
}
int pop(Stack* stack) {
int value = 0;
if(stack->queue1->front == stack->queue1->rear) {
printf("Stack is empty.\n");
return -1;
}
while(stack->queue1->front < stack->queue1->rear - 1) {
stack->queue2->data[stack->queue2->rear] = stack->queue1->data[stack->queue1->front];
stack->queue1->front++;
stack->queue2->rear++;
}
value = stack->queue1->data[stack->queue1->front];
stack->queue1->front++;
Queue* temp = stack->queue1;
stack->queue1 = stack->queue2;
stack->queue2 = temp;
return value;
}
int main() {
Stack* stack = createStack(10);
push(stack, 1);
push(stack, 2);
push(stack, 3);
printf("%d\n", pop(stack));
push(stack, 4);
printf("%d\n", pop(stack));
printf("%d\n", pop(stack));
printf("%d\n", pop(stack));
printf("%d\n", pop(stack));
return 0;
}
```
c++ 能否用两个栈实现一个队列的功能
是的,可以使用两个栈实现一个队列的功能。具体实现方法如下:
1. 定义两个栈,一个作为输入栈,一个作为输出栈。
2. 进队时,将元素压入输入栈。
3. 出队时,先判断输出栈是否为空,如果不为空,则直接弹出栈顶元素;如果为空,则先将输入栈中的所有元素都弹出并压入输出栈,然后再弹出输出栈的栈顶元素。
实现代码如下:
```c++
#include <stack>
class Queue {
public:
void push(int x) {
input_stack.push(x);
}
int pop() {
if (output_stack.empty()) {
while (!input_stack.empty()) {
output_stack.push(input_stack.top());
input_stack.pop();
}
}
int x = output_stack.top();
output_stack.pop();
return x;
}
bool empty() {
return input_stack.empty() && output_stack.empty();
}
private:
std::stack<int> input_stack;
std::stack<int> output_stack;
};
```
这样,就可以用两个栈实现一个队列的功能了。