[两个栈实现队列]
- 一、题目
- 二、思路
- 三、代码
一、题目
二、思路
//思路:两个栈实现队列,栈是先入后出,队列是队尾入,对头出,(先入先出),那么可以这样干,假设一个栈Pushst,先入1,2,3,4,那么成队列,先要出1,1在一个栈中是不可能出的,那么可以把Pushst的数据出栈放到另一个Popst中,顺序就转过来了,在Popst中出栈,就顺序合适了!
综上所述:队列Push:在一个栈中Pushst中如数据就可以了!
队列Pop:在另一个栈中Popst,如果Popst中没有数据,那么把Pushst中的数据全部放到Popst中即可,在Popst中出数据就可以了!
//下面把这个过程画出来!
三、代码
typedef int STDataType;
typedef struct Stack {
//存储数据
STDataType* a;
//栈顶
int Top;
//定义容量
int capacity;
}ST;
void STInit(ST* ps){
assert(ps);
ps->a = NULL;
ps->capacity = ps->Top = 0;
}
void STDestory(ST* ps) {
assert(ps);
free(ps->a);
ps->capacity = ps->Top = 0;
ps->a = NULL;
}
void STPush(ST* ps, STDataType x) {
assert(ps);
//扩容
if (ps->capacity == ps->Top) {
int newcapacity = (ps->capacity == 0 ? 4 : ps->capacity * 2);
STDataType* tmp = (STDataType*)realloc(ps->a,sizeof(STDataType)*newcapacity);
if (tmp == NULL) {
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity = newcapacity;
}
//存数据
ps->a[ps->Top] = x;
ps->Top++;
}
bool StEmpty(ST* ps) {
assert(ps);
return ps->Top == 0;
}
void STPop(ST* ps) {
assert(ps);
assert(ps->a);
assert(ps->Top);
ps->Top--;
}
int STTop(ST* ps) {
assert(ps);
assert(ps->a);
assert(ps->Top);
return ps->a[ps->Top - 1];
}
int STSize(ST* ps) {
assert(ps);
return ps->Top;
}
typedef struct {
ST Pushst; //push存数据的栈
ST Popst; //pop出数据的栈
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* obj = (MyQueue*)malloc(sizeof(MyQueue));
STInit(&obj->Pushst);
STInit(&obj->Popst);
return obj;
}
void myQueuePush(MyQueue* obj, int x) {
//向Pushst放数据
STPush(&obj->Pushst,x);
}
int myQueuePop(MyQueue* obj) {
//如果Popst里面没有数据,则把Pushst里面的数据放到Popst
//否则Popst出栈即可
if(StEmpty(&obj->Popst)){
//如果Popst为空,则把所有的Pushst的数据放到Popst
while(!StEmpty(&obj->Pushst)){
int Top = STTop(&obj->Pushst);
STPop(&obj->Pushst);
STPush(&obj->Popst,Top);
}
}
int Top = STTop(&obj->Popst);
STPop(&obj->Popst);
return Top;
}
int myQueuePeek(MyQueue* obj) {
if(StEmpty(&obj->Popst)){
//如果Popst为空,则把所有的Pushst的数据放到Popst
while(!StEmpty(&obj->Pushst)){
int Top = STTop(&obj->Pushst);
STPop(&obj->Pushst);
STPush(&obj->Popst,Top);
}
}
int Top = STTop(&obj->Popst);
return Top;
}
bool myQueueEmpty(MyQueue* obj) {
return StEmpty(&obj->Pushst) && StEmpty(&obj->Popst);
}
void myQueueFree(MyQueue* obj) {
STDestory(&obj->Pushst);
STDestory(&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);
*/