力扣刷题 -- 232. 用栈实现队列
1. 题目
2. 思路分析
1)创建两个栈空间,PushST,PopST;
2)插入数据往PushST插,判断PopST是否为空,如果为空直接往PopST出数据;如PopST不为空,就先把PopST的数据先出栈;
3)PopST全部出队列。
3. 代码实现
typedef int STDataType;
typedef struct Stack
{STDataType* arr;int top;//栈顶(相当于size)int capacity;//栈的大小
}ST;//初始化
void StackInit(ST* ps)
{ps->arr = NULL;ps->top = ps->capacity = 0;
}
//销毁
void StackDestroy(ST* ps)
{assert(ps);if (ps->arr != NULL){free(ps->arr);ps->arr = NULL;ps->capacity = ps->top = 0;}
}
//入栈
void StackPush(ST* ps, STDataType x)
{assert(ps);//入栈的前提:要有足够大的空间if (ps->top == ps->capacity)//空间不够{int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;STDataType* temp = realloc(ps->arr, newcapacity * sizeof(STDataType));if (temp == NULL){perror("realloc fail!");exit(1);}else//扩容成功{ps->arr = temp;ps->capacity = newcapacity;}}//空间够了,进行入栈ps->arr[ps->top] = x;ps->top++;
}
//判断栈顶为空
bool StackEmpty(ST* ps)
{assert(ps);return ps->top == 0;
}
//出栈
void StackPop(ST* ps)
{assert(ps);assert(!StackEmpty(ps));ps->top--;
}
//获取栈顶元素
STDataType Stacktop(ST* ps)
{assert(ps);return ps->arr[ps->top-1];
}
//获取栈顶元素有效个数
int StackSize(ST* ps)
{assert(ps);return ps->top;
}
///以上是栈的结构和相关方法///typedef struct {ST pushST;ST popST;
} MyQueue;MyQueue* myQueueCreate() {MyQueue* q=(MyQueue*)malloc(sizeof(MyQueue));StackInit(&q->pushST);StackInit(&q->popST);return q;
}
//入队列
void myQueuePush(MyQueue* obj, int x) {StackPush(&obj->pushST,x);
}int myQueuePop(MyQueue* obj) {//先判断popST是否为空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) {//先判断popST是否为空if(StackEmpty(&obj->popST)){while(!StackEmpty(&obj->pushST)){StackPush(&obj->popST,Stacktop(&obj->pushST));StackPop(&obj->pushST);}}int top=Stacktop(&obj->popST);return top;
}bool myQueueEmpty(MyQueue* obj) {return StackEmpty(&obj->pushST)&&StackEmpty(&obj->popST);
}void myQueueFree(MyQueue* obj) {StackDestroy(&obj->pushST);StackDestroy(&obj->popST);free(obj);obj=NULL;
}