请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:
你 只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
示例:
输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/implement-queue-using-stacks
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
由于使用栈来实现队列,所以这里需要一些必备的接口函数
栈的接口函数
void StackInit(ST* ps)
{
assert(ps);
ps->a = (STDataType*)malloc(sizeof(STDataType) * 4);
if (ps->a==NULL)
{
printf("malloc fail\n");
exit(-1);
}
ps->capacity = 4;
ps->top = 0;
//初始top=0,意味着top指向栈顶元素的下一个
//初始top=-1,意味着top指向栈顶元素
}
void StackDestory(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
void StackPush(ST* ps,STDataType x)
{
assert(ps);
if (ps->top==ps->capacity)
{
STDataType* tmp = (STDataType*)realloc(ps->a, ps->capacity * 2 * sizeof(STDataType));
if (tmp==NULL)
{
printf("realloc fail\n");
exit(-1);//终止程序
}
else
{
ps->a = tmp;
ps->capacity *= 2;
}
}
ps->a[ps->top] = x;
ps->top++;
}
void StackPop(ST* ps)
{
assert(ps);
assert(ps->top>0);//空栈时调用top直接终止程序报错
ps->top--;//直接将栈顶数据删除,下一次有数据入栈会覆盖top位置
}
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);
return ps->top == 0;//如果top为零,说明栈中没有元素,为空
//返回布尔值为1
}
由于栈的先进后出原则与队列的先进先出原则,所以采用两个栈来实现队列的进出功能,设置栈L1作为队列的进入实现,设置栈L2作为队列的弹出实现。
由于我在栈的实现中将栈顶初始值设置为0,所以top指向栈顶元素的下一个能插入的地方
在进行移除开头队列元素之前,我们需要判断弹出栈是否为空,如果为空则将其赋值与L1相同
代码实现:
typedef int STDataType;
typedef struct Queue
{
ST L1;
ST L2;
}MyQueue;
typedef struct Stack
{
int top;
int capacity;
STDataType* a;
}ST;
MyQueue* myQueueCreate()
{
MyQueue* Q1;
StackInit(&Q1->L1);
StackInit(&Q1->L2);
return Q1;
}
void myQueuePush(MyQueue* obj, int x)
{
StackPush(&obj->L1, x);
}
int myQueuePop(MyQueue* obj)
{
if (StackEmpty(&obj->L2))
{
while (!StackEmpty(&obj->L1))
{
StackPush(&obj->L2, StackTop(&obj->L1));
StackPop(&obj->L1);
}
}
int x = StackTop(&obj->L2);
StackPop(&obj->L2);
return x;
}
int myQueuePeek(MyQueue* obj)
{
if (StackEmpty(&obj->L2))
{
while (!StackEmpty(&obj->L1))
{
StackPush(&obj->L2, StackTop(&obj->L1));
StackPop(&obj->L1);
}
}
int top=StackTop(&obj->L2);
return top;
}
bool myQueueEmpty(MyQueue* obj)
{
if (obj->L1.top==0&&obj->L2.top==0)
{
return true;
}
return false;
}
void myQueueFree(MyQueue* obj)
{
StackDestory(&obj->L1);
StackDestory(&obj->L2);
}
运行结果: