题目要求
出队操作
假设有四个有效元素1,2,3,4依次存入,
出栈顺序:4,3,2,1.
出队顺序:1,2,3,4.
此时出栈操作只能出栈的最后一个元素4,而出队操作出的是队列的第一个元素1,此时我们可以再定义一个副栈,将前3个元素出栈再入栈到副栈中,再对主栈进行出栈操作,就实现了1的出栈,封装后可视为出队操作,图解:
leetcode题目链接:用栈实现队列
完整代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
typedef int stdatatype;
typedef struct stack {
stdatatype* data;
int size;
int capacity;
}stack;
//初始化
void Initstack(stack* st)
{
if (st == NULL)
return;
st->data = NULL;
st->capacity = st->size = 0;
}
//检查容量
void Checkcapacity(stack*st)
{
if (st->size == st->capacity)
{
int newcapacity=st->capacity == 0 ? 1 : 2 * st->capacity;
st->data = (stdatatype*)realloc(st->data, sizeof(stdatatype)*newcapacity);
st->capacity = newcapacity;
}
}
//入栈
void Stackpush(stack* st, stdatatype val)
{
if (st == NULL)
return;
Checkcapacity(st);
st->data[st->size++] = val;
}
//出栈
void Stackpop(stack* st)
{
if (st == NULL||st->size==0)
return;
st->size--;
}
//获取栈中元素个数
int Satcksize(stack* st)
{
if (st == NULL)
return 0;
return st->size;
}
//判断栈空
int Emptystack(stack*st)
{
if (st == NULL || st->size == 0)
return 1;
else
return 0;
}
//获取栈顶元素
stdatatype Stacktop(stack* st)
{
return st->data[st->size - 1];
}
//销毁栈
void Destorystack(stack*st)
{
if(st)
{
if(st->data)
{
free(st->data);
st->data = NULL;
st->size = 0;
st->capacity = 0;
}
}
}
//判断栈空
int StackEmpty(stack* st)
{
return st->size==0;
}
typedef struct {
struct stack pushst; //主栈
struct stack popst; //副栈
} MyQueue;
/** Initialize your data structure here. */
MyQueue* myQueueCreate() {
MyQueue*p=(MyQueue*)malloc(sizeof(MyQueue));
Initstack(&p->pushst);
Initstack(&p->popst);
return p;
}
/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {
Stackpush(&obj->pushst,x);
}
/** Removes the element from in front of queue and returns that element. */
int myQueuePop(MyQueue* obj) {
int front;
if(!StackEmpty(&obj->popst))
{
front = Stacktop(&obj->popst);
Stackpop(&obj->popst);
}
else
{
while(!StackEmpty(&obj->pushst))
{
Stackpush(&obj->popst,Stacktop(&obj->pushst));
Stackpop(&obj->pushst);
}
front =Stacktop(&obj->popst);
Stackpop(&obj->popst);
}
return front;
}
/** Get the front element. */
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);
}
else
{
return Stacktop(&obj->popst);
}
}
/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
return StackEmpty(&obj->popst)&&StackEmpty(&obj->pushst);
}
void myQueueFree(MyQueue* obj) {
Destorystack(&obj->pushst);
Destorystack(&obj->popst);
free(obj);
}
/**
* Your MyQueue struct will be instantiated and called as such:
* MyQueue* obj = myQueueCreate();
* myQueuePush(obj, x);
* int param_2 = myQueuePop(obj);
* int param_3 = myQueuePeek(obj);
* bool param_4 = myQueueEmpty(obj);
* myQueueFree(obj);
*/