题⽬描述:
⽤两个栈来实现⼀个队列,使⽤n个元素来完成n次在队列尾部插⼊整数(push)和n次在队列
头部删除整数(pop)的功能。队列中的元素为int类型。保证操作合法,即保证pop操作时队
列内已有元素。
数据范围:0≤n≤5000,数组中每个数的值0≤val≤10000
要求:时间复杂度O(n),空间复杂度O(n)
进阶:时间复杂度O(n^2),空间复杂度O(1)
思路
1、队列性质:先进先出。
2、对于栈,后进先出。
3、⼀个栈实现⼊队列,push()即栈1。⼀个栈实现出队列pop()即栈2
4、另外需要⼀个a作为中间数值。
压先调⽤1栈压⼊元素。
①c语言实现:
// 定义栈结构
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
// 初始化栈
void initStack(Stack* stack) {
stack->top = -1;
}
// 判断栈是否为空
bool isEmpty(Stack* stack) {
return stack->top == -1;
}
// 判断栈是否已满
bool isFull(Stack* stack) {
return stack->top == MAX_SIZE - 1;
}
// 入栈操作
void push(Stack* stack, int value) {
if (isFull(stack)) {
printf("Stack is full\n");
return;
}
stack->top++;
stack->data[stack->top] = value;
}
// 出栈操作
int pop(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
}
int value = stack->data[stack->top];
stack->top--;
return value;
}
// 定义队列结构
typedef struct {
Stack stack_push; // 用于插入元素的栈
Stack stack_pop; // 用于删除元素的栈
} Queue;
// 初始化队列
void initQueue(Queue* queue) {
initStack(&(queue->stack_push));
initStack(&(queue->stack_pop));
}
// 入队操作
void pushQueue(Queue* queue, int value) {
push(&(queue->stack_push), value);
}
// 出队操作
int popQueue(Queue* queue) {
if (isEmpty(&(queue->stack_push)) && isEmpty(&(queue->stack_pop))) {
return -1;//判断队列是否为空
}
if (isEmpty(&(queue->stack_pop))) {
// 将stack_push中的元素压入stack_pop中
while (!isEmpty(&(queue->stack_push))) {
int value = pop(&(queue->stack_push));
push(&(queue->stack_pop), value);
}
}
return pop(&(queue->stack_pop));
}
②c++实现:
#include<iostream>
#include <algorithm>
#include <stack>
using namespace std;
stack<int> stack1;
stack<int> stack2;
void push1(int node) {
stack1.push(node);
}
void push2(int node) {
int temp = stack1.top();
stack1.top();
stack2.push(temp);
}
void pop() {
while( !stack2.empty() ) {
int ans = stack2.top();
stack2.pop();
//把输出当作弹出
cout << ans << " ";
}
}
void main() {
int len , temp;
cout << "请输入长度";
cin >> len;
for( int i = 0; i < len; i++ ) {
//先把数据全部压入第一个栈
cin >> temp;
push1(temp);
}
for( int i = 0; i < len; i++ ) {
//再把第一个栈的数据弹出到第二个栈
temp = stack1.top();
stack2.push(temp);
stack1.pop();
}
//最后把第二个栈的数据弹出就是先进先出了
pop();
}