解题思路:
pushst用于入队操作,popst用于出队操作。
1.当需要入队时,元素被压入 pushst 栈中。当需要出队时,如果 popst 栈为空,则将 pushst 栈中的元素依次弹出并压入 popst 栈中,然后从 popst 栈中弹出popst的栈顶元素(popst的栈顶元素即为队列中的队头元素)。这样就实现了队列的先进先出特性。
2.当再次入队列时,要把新加入的元素压入栈 pushst 而不是栈 popst 中,因为栈 pushst 负责入队列,而栈 popst 用于出队列。当栈 popst 为空时,才可以把新压入栈 pustst 中的全部元素压入到栈 popst 中。再次出栈依然时之前出栈的步骤。
3.当两个栈均为空时,队列为空。
C语言实现代码:
//附用Stack实现代码 typedef int STDataType; typedef struct Stack { STDataType* a; int top; int capacity; }ST; void StackInit(ST* ps); void StackDestroy(ST* ps); void StackPush(ST* ps,STDataType x); void StackPop(ST* ps); STDataType StackTop(ST* ps);//取栈顶的数据 int StackSize(ST* ps); bool StackEmpty(ST* ps); void StackInit(ST* ps) { assert(ps); ps->a = NULL; ps->capacity = 0; ps->top = 0; } void StackDestroy(ST* ps) { assert(ps); free(ps->a); ps->a = NULL; ps->capacity = ps->top = 0; } void StackPush(ST* ps, STDataType x) { assert(ps); if (ps->capacity == ps->top) { int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2; STDataType* tmp = realloc(ps->a, sizeof(STDataType) * newCapacity); if (tmp == NULL) { printf("realloc fail\n"); exit(-1); } ps->a = tmp; ps->capacity = newCapacity; } ps->a[ps->top] = x; ps->top++; } void StackPop(ST* ps) { assert(ps); assert(!StackEmpty(ps)); ps->top--; } STDataType StackTop(ST* ps) { assert(ps); assert(!StackEmpty(ps)); 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; } typedef struct { ST popst; ST pushst; } MyQueue; MyQueue* myQueueCreate() { MyQueue* obj = (MyQueue*)malloc(sizeof(MyQueue)); if(obj == NULL) { perror("malloc fail"); return NULL; } StackInit(&obj->pushst); StackInit(&obj->popst); return obj; } void myQueuePush(MyQueue* obj, int x) { StackPush(&obj->pushst,x); } int myQueuePeek(MyQueue* obj) { if(StackEmpty(&obj->popst)) { while(!StackEmpty(&obj->pushst)) { StackPush(&obj->popst,StackTop(&obj->pushst)); StackPop(&obj->pushst); } } int front = StackTop(&obj->popst); return front; } int myQueuePop(MyQueue* obj) { int front = myQueuePeek(obj); StackPop(&obj->popst); return front; } bool myQueueEmpty(MyQueue* obj) { return StackEmpty(&obj->pushst)&&StackEmpty(&obj->popst); } void myQueueFree(MyQueue* obj) { StackDestroy(&obj->pushst); StackDestroy(&obj->popst); free(obj); }