您的位置:首页 > Web前端

【剑指offer】用两个栈实现队列

2014-07-01 15:53 393 查看
题目:用两个栈实现一个队列。队列的声明如下:请实现它的两个函数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、注意画图对分析程序的帮助。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: