堆栈

               (不知道说什么啊,老师讲的东西,总结下。 这些是一些简单的堆栈处理,即学习使用.h ,好吧 ,不多说了)

下面是.h文件

#ifndef _STACK_H_ //如果没有定义_STACK_H_
#define _STACK_H_ //定义_STACK_H_

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

#define TRUE 1
#define FALSE 0

typedef unsigned char boolean;
typedef int ErrorNo;//错误序号
//操作系统的两个基本功能:用户接口 程序员接口
//程序员接口:

ErrorNo errNo;

#define NO_ERROR 0
#define ERR_NO_ROOM -1
#define ERR_STACK_ALREADY_EXISTS -2

char *errMsg[] = //向量表,向量(首地址 指针(函数指针,数组指针))
{
"无错误。",
"申请空间失败。",
"堆栈已存在,不能初始化"
};
void showErrMsg(); //错误消息显示

void showErrMsg()
{
printf("\n错误:(%d):%s\n",-errNo,errMsg[-errNo]);
}

typedef struct STACK //结构体定义
{
USER_TYPE *stack;
int maxRoom;
int top;
}STACK;

boolean initStack(STACK **hp,int maxRoom);
void destoryStack(STACK **hp);
boolean isStackEmpty(STACK stack);
boolean isStackFull(STACK stack);
boolean push(STACK *sp,USER_TYPE value);
boolean pop(STACK *sp,USER_TYPE *valuePoint);
boolean readTop(STACK stack,USER_TYPE *valuePoint);

boolean readTop(STACK stack,USER_TYPE *valuePoint)
{
boolean OK = TRUE;

if(!isStackEmpty(stack))
{
*valuePoint = stack.stack[stack.top-1];
}
else
{
OK = FALSE;
}
return OK;

}
boolean pop(STACK *sp,USER_TYPE *valuePoint)
{
boolean OK = TRUE;

if(!isStackFull(*sp))
{
*valuePoint = sp->stack[--sp->top];
}
else
{
OK = FALSE;
}
return OK;

}

boolean push(STACK *sp,USER_TYPE value)
{
boolean OK = TRUE;

if(!isStackFull(*sp))
{
sp->stack[sp->top++] = value;
}
else
{
OK = FALSE;
}

return OK;
}

boolean isStackEmpty(STACK stack)
{
return 0 == stack.top;

}

boolean isStackFull(STACK stack)
{
return stack.maxRoom <= stack.top;

}

void destoryStack(STACK **hp)
{
STACK *p;
p = *hp;
free(p->stack);
free(p);
*hp = NULL;
}

boolean initStack(STACK **hp,int maxRoom)
{
boolean OK = TRUE;
if(NULL == *hp)
{
*hp = (STACK *)calloc(sizeof(STACK),1);
if(NULL == *hp)
{
OK = FALSE;
errNo = ERR_NO_ROOM;
}
else
{
STACK *h;
h = *hp;
h->stack = (USER_TYPE *)calloc(sizeof(USER_TYPE), maxRoom);
if(!h->stack) // <=> if(h->stack == NULL)
{
OK = FALSE;
errNo = ERR_NO_ROOM;
free(h);
*hp = NULL;
}
else
{
h->maxRoom = maxRoom;
h->top = 0;
}
}
}
else
{
OK = FALSE;
errNo = ERR_STACK_ALREADY_EXISTS;
}

return OK;

}
#endif

下面是.c文件

#include <stdio.h>

typedef int USER_TYPE;

#include "STACK.h"

int main(void)
{
STACK *s1=NULL; //防止野指针
STACK *s2=NULL;

initStack(&s1,30);
destoryStack(&s1);
return 0;
}

                                                                                                                                                                                           by :暖暖要坚持

                                                                                                                                                                                           20150518

posted @ 2015-05-18 17:07  暖暖要坚持  阅读(228)  评论(0编辑  收藏  举报