(C语言)栈的线性结构实现(数据结构八)

1.数据类型定义

在代码中为了清楚的表示一些错误和函数运行状态,我们预先定义一些变量来表示这些状态。在head.h头文件中有如下定义:

//定义数据结构中要用到的一些变量和类型
#ifndef HEAD_H
#define HEAD_H

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

#define TRUE  1
#define FALSE 0
#define OK    1
#define ERROR  0
#define INFEASIBLE -1
#define OVERFLOW   -2    //分配内存出错

typedef int  Status;     //函数返回值类型
typedef int  ElemType;   //用户定义的数据类型

#endif

2.栈数据结构定义:

typedef struct Stack{
	ElemType *base;   //栈底
	ElemType *top;    //栈顶
	int     size;    //栈大小
}Stack,*pStack;

3.栈线性结构实现:

LinearStack.h中实现栈的代码如下:

#ifndef LINEAR_STACK
#define LINEAR_STACK
#include "head.h"

#define  STACK_INIT_SIZE 100  
#define  STACK_INCREMENT 10    

typedef struct Stack{
	ElemType *base;   //栈底
	ElemType *top;    //栈顶
	int     size;    //栈大小
}Stack,*pStack;

//初始化栈
Status InitStack(pStack &S){
	S=(pStack)malloc(sizeof(Stack));
	ElemType* p=(ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
	if(!p) return OVERFLOW;
	S->base=p;
	S->top=p;
	S->size=STACK_INIT_SIZE;
	return OK;
}

Status freeStack(pStack &S){
	free(S);
	S=NULL;
	return OK;
}
//销毁栈
Status DestroyStack(pStack &S){
	free(S->base);
	S->base=NULL;
	S->top=NULL;
	freeStack(S);
	return OK;
}
//清空栈
Status ClearStack(pStack &S){
	S->top=S->base;
	return OK;
}
//栈是否为空
Status StaciEmpty(pStack S){
	return S->top==S->base;
}
//栈长度
int StackLength(pStack S){
	return S->top-S->base;
}
//得到栈顶数据级e
Status GetTop(pStack S,ElemType &e){
	e=*(S->top-1);
	return OK;
}
//入栈
Status Push(pStack &S,ElemType e){
	if(StackLength(S)>=S->size)
		S->base=(ElemType*)realloc(S->base,(S->size+STACK_INCREMENT)*sizeof(ElemType));
	if(!S->base) return OVERFLOW;
	S->top=S->base+StackLength(S);
	S->size+=STACK_INCREMENT;
	*S->top++=e;
	return OK;
}
//出栈
Status Pop(pStack &S,ElemType &e){
	if(StackLength(S)<1) return ERROR;
		e=*--S->top;
	return OK;
}

Status print(ElemType e){
	printf("%d\n",e);
	return OK;
}

//用vistit遍历栈
Status StackTraverse(pStack S,Status(*visit)(ElemType)){
	while (S->top>S->base)
		(*visit)(*--S->top);
	return OK;
}
Status printStack(pStack S){
	StackTraverse(S,print);
	return OK;
}



#endif
4.测试

#include "LinearStack.h"
void main(){
	pStack S;
	InitStack(S);
	for (int i=0;i<10;i++)
		Push(S,i);
	ElemType e;
	GetTop(S,e);
	printf("栈顶:%d 栈长度:%d",e,StackLength(S));

	printf("\n输出栈:\n");
	printStack(S);
	
	ClearStack(S);   //清空栈
	DestroyStack(S); //销毁栈

}



5.测试结果

栈顶:9 栈长度:10
输出栈:
9
8
7
6
5
4
3
2
1
0





posted @ 2013-10-11 16:44  赵侠客  阅读(351)  评论(0编辑  收藏  举报