题海拾贝:力扣 232.用栈实现队列
Hello大家好!很高兴我们又见面啦!给生活添点passion,开始今天的编程之路!
我的博客:<但凡.
我的专栏:《编程之路》、《数据结构与算法之美》、《题海拾贝》
欢迎点赞,关注!
1、题目
题目链接:232. 用栈实现队列 - 力扣(LeetCode)
2、题解
//快速写一下
typedef int STdate;
typedef struct stack
{
STdate* arr;//数组模拟栈
int top;
int capacity;
}ST;
void InitST(ST* stack)
{
stack->arr = NULL;
stack->capacity = 0;//能存放的最大数据个数
stack->top = 0;//有效数据个数
}
void Destory(ST* stack)
{
if (stack->arr)
{
free(stack->arr);
stack->arr = NULL;
}
stack->capacity = 0;//能存放的最大数据个数
stack->top = 0;//有效数据个数
}
void STpush(ST* stack, STdate x)
{
assert(stack);
//判断是否还有空间
if (stack->top == stack->capacity)
{
int newcapacity = stack->capacity ? 2 * stack->capacity : 1;
STdate* p = (STdate*)realloc(stack->arr, newcapacity * sizeof(int));
if (p == NULL)
{
exit(1);
}
stack->arr = p;
stack->capacity = newcapacity;
}
stack->arr[stack->top] = x;
stack->top++;
}
bool STempty(ST* stack)
{
if (stack->top != 0)
{
return false;
}
else
{
return true;
}
}
void STpop(ST* stack)
{
assert(!STempty(stack));
stack->top--;
}
int STsize(ST* stack)
{
return stack->top;
}
int STtop(ST* stack)
{
assert(stack);
return stack->arr[stack->top - 1];
}
//以上是栈的操作
typedef struct {
//包含两个栈
ST STpush;
ST STpop;
} MyQueue;
//初始化
MyQueue* myQueueCreate() {
MyQueue* qu=(MyQueue*)malloc(sizeof(MyQueue));
InitST(&qu->STpush);
InitST(&qu->STpop);
return qu;
}
void myQueuePush(MyQueue* obj, int x) {
//插入元素就往插入元素的栈里插入就行
STpush(&obj->STpush,x);
}
int myQueuePop(MyQueue* obj) {
//在删除栈为空的情况下
//删除需要把插入栈里的所有元素都转移到删除栈里,然后再弹出栈顶
if(STempty(&obj->STpop))
{
while(!STempty(&obj->STpush))
{
STpush(&obj->STpop,STtop(&obj->STpush));
STpop(&obj->STpush);
}
}
int ele=STtop(&obj->STpop);
STpop(&obj->STpop);
return ele;
}
int myQueuePeek(MyQueue* obj) {
//在删除栈为空的情况下
//删除需要把插入栈里的所有元素都转移到删除栈里,然后再弹出栈顶
if(STempty(&obj->STpop))
{
while(!STempty(&obj->STpush))
{
STpush(&obj->STpop,STtop(&obj->STpush));
STpop(&obj->STpush);
}
}
int ele=STtop(&obj->STpop);//队列开头元素
return ele;
}
bool myQueueEmpty(MyQueue* obj) {
return STempty(&obj->STpush)&&STempty(&obj->STpop);
}
void myQueueFree(MyQueue* obj) {
Destory(&obj->STpush);
Destory(&obj->STpop);
free(obj);
obj=NULL;
}
/**
* 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);
*/
好了,今天的内容就分享到这,我们下期再见!