【剑指offer】用两个栈实现队列
2014-07-01 15:53
393 查看
题目:用两个栈实现一个队列。队列的声明如下:请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
分析:
队列的特点是“先进先出”,而栈的特点是“先进后出”。要用两个栈来实现队列。用图分析如下:
程序代码如下:
注意:上面的代码只是简单的实现了两个栈实现队列的功能,但没有普适性,而且只是一个交互性几乎没有。
总结:
1、了解栈以及队列的特点。
2、注意画图对分析程序的帮助。
分析:
队列的特点是“先进先出”,而栈的特点是“先进后出”。要用两个栈来实现队列。用图分析如下:
程序代码如下:
#include <stdio.h> #include <stdlib.h> #include <memory.h> #ifndef ERROR #define ERROR (0) #endif #ifndef OK #define OK (!ERROR) #endif #define STACK_INIT_SIZE 1 #define STACKINCREMENT 10 typedef int SElemType; typedef struct SqStack{ SElemType *base; SElemType *top; int stacksize; }SqStack, *pStack; pStack S1, S2; pStack InitStack(pStack S); pStack Push(pStack S, SElemType e); SElemType Pop(pStack S); void QueueInput(int number); int QueueOutput(); int main(void) { S1 = InitStack(S1); S2 = InitStack(S2); QueueInput(3); QueueInput(8); QueueInput(5); printf("output is %d\n",QueueOutput()); return 0; } pStack InitStack(pStack S) { S = (pStack)malloc(STACK_INIT_SIZE * sizeof(SElemType)); if(S == NULL){ return ERROR; } S->base = (SElemType *)S; S->top = S->base; S->stacksize = STACK_INIT_SIZE; return S; } pStack Push(pStack S, SElemType e) { if((S->top - S->base) >= S->stacksize){ S->base = (SElemType *)realloc(S, (S->stacksize + STACKINCREMENT)*sizeof(SElemType)); if(S->base == NULL) return ERROR; S->top = S->base + S->stacksize; S->stacksize += STACKINCREMENT; } *S->top++ = e; return S; } SElemType Pop(pStack S) { if(S->top == S->base) return 0; return *(--S->top); } void QueueInput(int number) { Push(S1, number); } int QueueOutput() { Push(S2,Pop(S1)); Push(S2,Pop(S1)); Push(S2,Pop(S1)); return Pop(S2); }
注意:上面的代码只是简单的实现了两个栈实现队列的功能,但没有普适性,而且只是一个交互性几乎没有。
总结:
1、了解栈以及队列的特点。
2、注意画图对分析程序的帮助。
相关文章推荐
- [剑指offer][面试题07]用两个栈实现队列
- 【剑指offer】两个队列实现一个栈
- 【剑指offer】两个队列实现堆栈
- 【剑指offer】面试题七:用两个栈实现队列
- 剑指offer--面试题7:用两个栈实现队列--Java实现
- [剑指offer][面试题07-扩展]用两个队列实现栈
- 剑指offer 面试题7 两个栈实现队列
- 剑指offer之用两个栈实现队列
- 【剑指Offer面试编程题】题目1512:用两个栈实现队列--九度OJ
- 剑指offer:用两个栈实现队列
- 剑指Offer - 九度1512 - 用两个栈实现队列
- 剑指Offer:面试题7 用两个栈实现队列
- 【剑指offer】面试题:两个队列实现栈
- 剑指offer面试题7——用两个栈实现队列
- 剑指offer-->面试题7 用两个栈实现队列
- 【剑指offer】两个栈实现一个队列
- 【剑指offer】面试题7:用两个栈实现队列
- [九度1512 剑指offer7] 用两个栈实现队列
- [剑指OFFER] 用两个栈实现队列
- 【剑指Offer学习】【面试题7:用两个栈实现队列】