题目
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/implement-queue-using-stacks
核心思路
栈的特点是先进后出,队列的特点是先进先出
1.自己实现栈
2.用两个栈实现队列
3.入列时,两个栈一个是输出栈,一个是输入栈,入列时把数据向输入栈插入
4.出列时,把输出栈的栈顶数据删除,如果输出栈没有数据,就将输入栈的全部数据移动到输出栈里面
5.返回对头数据时,要将输出栈的栈顶数据返回,如果输出栈没有数据,就将输入栈的全部数据移动到输出栈中
6.判断队列为不为空时,只有两个栈皆空队列才为空
细节
这里肯定就会有人不明白,输出栈的栈顶数据为什么就是对头的数据,为什么和两队列实现栈不同
开始移动数据到输出栈
这时我们会惊奇的发现数据的顺序就是我们想要的顺序,队列的特点是先进先出因为我们插入的顺序是1,2,3,4所以输出的顺序也应该是1,2,3,4,看图我们又发现输出栈栈顶到栈底的数据顺序也是1,2,3,4。
再入列时
再出列
注意只有输出栈为空时才能把输入栈的数据移动到输出栈上
代码
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int capacity;
int top;
}ST;
void StackInit(ST* ps);
void StackPush(ST* ps, STDataType x);
void StackPop(ST* ps);
void StackDestroy(ST* ps);
STDataType StackTop(ST* ps);
int StackSize(ST* ps);
bool StackEmpty(ST* ps);
void StackInit(ST* ps)
{
ps->a = NULL;
ps->capacity = 0;
ps->top = 0;
}
void StackPush(ST* ps, STDataType x)
{
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* pf = realloc(ps->a, sizeof(STDataType) * newcapacity);
if (pf == NULL)
{
printf("realloc fail");
exit(-1);
}
ps->a = pf;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
void StackPop(ST* ps)
{
assert(ps);
assert(ps->top > 0);
ps->top--;
}
void StackDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = 0;
ps->top = 0;
}
STDataType StackTop(ST* ps)
{
assert(ps);
assert(ps->top != 0);
return ps->a[ps->top - 1];
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
bool StackEmpty(ST* ps)
{
assert(ps);
if (ps->top == 0)
{
return true;
}
else
{
return false;
}
}
//以上代码为栈的实现
typedef struct
{
ST PushST;
ST PopST;
} MyQueue;
MyQueue* myQueueCreate()
{
MyQueue* Queue = (MyQueue*)malloc(sizeof(MyQueue));
StackInit(&Queue->PushST);
StackInit(&Queue->PopST);
return Queue;
}
void myQueuePush(MyQueue* obj, int x)
{
StackPush(&obj->PushST, x);
}
int myQueuePop(MyQueue* obj)
{
if (StackEmpty(&obj->PopST))
{
while (!StackEmpty(&obj->PushST))
{
StackPush(&obj->PopST, StackTop(&obj->PushST));
StackPop(&obj->PushST);
}
}
int top = StackTop(&obj->PopST);
StackPop(&obj->PopST);
return top;
}
int myQueuePeek(MyQueue* obj)
{
if (StackEmpty(&obj->PopST))
{
while (!StackEmpty(&obj->PushST))
{
StackPush(&obj->PopST, StackTop(&obj->PushST));
StackPop(&obj->PushST);
}
}
return StackTop(&obj->PopST);
}
bool myQueueEmpty(MyQueue* obj)
{
return StackEmpty(&obj->PopST) && StackEmpty(&obj->PushST);
}
void myQueueFree(MyQueue* obj)
{
StackDestroy(&obj->PushST);
StackDestroy(&obj->PopST);
free(obj);
}
本文含有隐藏内容,请 开通VIP 后查看