题目:用两个栈实现一个队列。队列的声明如下:请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
分析:
队列的特点是“先进先出”,而栈的特点是“先进后出”。要用两个栈来实现队列。用图分析如下:
程序代码如下:
#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】用两个栈实现队列,布布扣,bubuko.com
原文:http://blog.csdn.net/to_be_it_1/article/details/36187465