两栈共享空间

代码内容来自《大话数据结构》

#include<stdio.h>

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

#define MAXSIZE	20

typedef int Status;
typedef int SElemType;

typedef struct SqDoubleStack{
	SElemType data[MAXSIZE];
	int top1;
	int top2;
}SqDoubleStack;

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

Status InitStack(SqDoubleStack *S){
	S->top1 = -1;
	S->top2 = MAXSIZE;
	return OK;
}

Status ClearStack(SqDoubleStack *S){
	S->top1 = -1;
	S->top2 = MAXSIZE;
	return OK;
}

Status StackEmpty(SqDoubleStack S){
	if(S.top1 == -1 && S.top2 == MAXSIZE){
		return TRUE;
	}
	return FALSE;
}

int StackLength(SqDoubleStack S){
	return (S.top1+1) + (MAXSIZE - S.top2);
}

Status Push(SqDoubleStack *S,SElemType e,int stackNumber){
	if(S->top1 + 1 == S->top2){
		return ERROR;
	}
	if(stackNumber == 1){
		S->data[++S->top1] = e;
	} else if(stackNumber == 2){
		S->data[--S->top2] = e;
	}
	return OK;
}

Status Pop(SqDoubleStack *S,SElemType *e,int stackNumber){
	if(stackNumber == 1){
		if(S->top1 == -1){
			return ERROR;
		}
		*e = S->data[S->top1--];
	} else  if(stackNumber == 2){
		if(S->top2 == MAXSIZE){
			return ERROR;
		}
		*e = S->data[S->top2++];
	}
	return OK;
}

Status StackTraverse(SqDoubleStack S){
	int i;
	i = 0;
	while(i<=S.top1){
		visit(S.data[i++]);
	}
	i = S.top2;
	while(i<MAXSIZE){
		visit(S.data[i++]);
	}
	printf("\n");
	return OK;
}

int main(){
	int j;
	SqDoubleStack S;
	int e;
	Status i;
	if(InitStack(&S)){
		printf("初始化成功");
	} else {
		printf("初始化成功");
		return 1;
	}
	for(j = 1; j <= 5; j++){
		Push(&S,j*2,1);
	}
	for(j = 1; j <= 5; j++){
		Push(&S,j*3,2);
	}
	StackTraverse(S);
	printf("栈长度 %d\n",StackLength(S));

	Pop(&S,&e,2);
	StackTraverse(S);

	Pop(&S,&e,1);
	StackTraverse(S);
	
	printf("栈是否为空 %d\n",StackEmpty(S));

	for(j = 1; j <= 6; j++){
		Push(&S,j*2,1);
	}
	for(j = 1; j <= 6; j++){
		Push(&S,j*3,2);
	}

	StackTraverse(S);
	printf("栈长度 %d\n",StackLength(S));
	if(Push(&S,99,1)){
		printf("栈未满\n");
	} else{
		printf("栈满\n");
	}
}

  

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