栈--顺序存储

代码内容来自《大话设计模式》

#include<stdio.h>

#define OK 		1
#define ERROR 	0
#define TRUE 	1
#define FALSE	0

#define MAXSIZE 20

typedef int Status;
typedef int SElemType;

struct SqStack{
	SElemType data[MAXSIZE];
	int top;
};

Status visit(SElemType c){
	printf("%d ",c);
	return OK;
}

Status InitStack(struct SqStack *S){
	S->top = -1;//-1表示栈底
	return OK;
}

Status ClearStack(struct SqStack *S){
	S->top = -1;
	return OK;
}

Status StackEmpty(struct SqStack S){
	if(S.top == -1){
		return TRUE;
	}
	return FALSE;
}

//第一个元素(栈底元素为0)
int StackLength(struct SqStack S){
	return S.top + 1;
}

Status GetTop(struct SqStack S,SElemType *e){
	if(S.top == -1){
		return ERROR;
	}
	*e = S.data[S.top];
	return OK;
}

Status Push(struct SqStack *S,SElemType e){
	if(S->top == MAXSIZE-1){
		return ERROR;//栈满
	}
	S->data[++S->top] = e;
	return OK;
}

Status Pop(struct SqStack *S,SElemType *e){
	if(S->top == -1){
		return ERROR;//空栈
	}
	*e = S->data[S->top--];
	return OK;
}

Status StackTraverse(struct SqStack S){
	int i = 0;
	while(i <= S.top){
		visit(S.data[i++]);
	}
	printf("\n");
	return OK;
}

int main(){
	int j;
	int e;
	struct SqStack S;
	if( ! InitStack(&S)){
		printf("初始化栈失败");
		return 1;
	} 
	for(j=1;j<10;j++){
		Push(&S,j*2);
	}
	StackTraverse(S);

	Pop(&S,&e);
	printf("弹出的元素为 %d\n",e);

	printf("栈是否为空 %d\n",StackEmpty(S));

	GetTop(S,&e);
	printf("栈顶元素为 %d\n",e);

	printf("栈长度 %d\n",StackLength(S));

	ClearStack(&S);
	printf("清空栈之后的长度 %d\n",StackLength(S));
	return 0;
}

  

posted @ 2018-04-14 16:55  寻觅beyond  阅读(206)  评论(0)    收藏  举报
返回顶部