天天看點

資料結構——順序棧的簡單實作

//順序棧的實作
#include<stdio.h>
#define Maxsize 200
typedef struct SqStack{
	int data[Maxsize];
	int top;
}SqStack;

//初始化棧 
void InitStack(SqStack &S){
	S.top = -1;
}

//判棧空
bool StackEmpty(SqStack S){
	if(S.top == -1)
		return true;
	else
		return false;
}

//進棧
bool Push(SqStack &S,int x){
	if(S.top == Maxsize - 1)
		return false;
		S.data[++S.top]=x;
		return true;
} 

//出棧
int Pop(SqStack &S,int x){
	if(S.top == -1)
		return -1;
	x=S.data[S.top];
	return x;
} 

//讀棧頂元素
bool GetTop(SqStack S,int &x){
	if(S.top==-1)
		return false;
	x = S.data[S.top];
	return true;
} 

int main(){
	SqStack stack;
	InitStack(stack);
	int x,j,result;
	bool empty;
	printf("(入棧操作)請輸入要入棧元素的個數:\n");
	scanf("%d",&j);
	printf("請輸入入棧元素:\n");
	for(int i = 0;i < j;i++){
		scanf("%d",&x);
		Push(stack,x);
	}
	GetTop(stack,result);
	printf("棧頂元素是:\t%d\n",result);
	empty = StackEmpty(stack);
	if(empty)
		printf("目前棧為空!\n");
	else
		printf("目前棧不為空\n");
	printf("出棧結果如下:\n");
	printf("\t┌───────────────┐\n");
	while(stack.top != -1){
		result = Pop(stack,result);
		printf("\t│\t%d\t│\n",result);
		if(stack.top!=0)
			printf("\t├───────────────┤\n");
		else
			printf("\t└───────────────┘\n");
		stack.top--;
	}
	empty = StackEmpty(stack);
	if(empty)
		printf("目前棧為空!\n");
	else
		printf("目前棧不為空\n");
	return 0;
}