操作受限的線性表:順序棧

棧(stack):操作受限的線性表
棧的順序存儲實現:順序棧

//棧(stack)--操作受限的線性表
//棧的順序存儲實現--順序棧
//ElemType:int 
#include<stdio.h>
#define MaxSize 10
typedef struct{
	int data[MaxSize];//靜態數組存放棧中元素 
	int top;//棧頂指針指向棧頂元素的位置(下標),棧空爲-1 
}SqStack;

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

//not important functions 
bool StackEmpty(SqStack S){//檢查是否爲空棧 
	if(S.top==-1)return true;
	else return false;
}

//important functions
bool Push(SqStack &S,int x){//新元素入棧 
	if(S.top+1==MaxSize)return false;//棧滿報錯
	S.data[++S.top]=x;
	return true;
}
bool Pop(SqStack &S,int &x){//出棧並將棧頂元素賦給x傳回 
	if(S.top==-1)return false;//空棧報錯 
	x=S.data[S.top--];
	return true;
}
bool GetTop(SqStack &S,int &x){//讀取棧頂元素 
	if(S.top==-1)return false;//空棧報錯 
	x=S.data[S.top];
	return true;
}

int main(){
	SqStack S;
	InitStack(S);
	Push(S,1);
	Push(S,2);
	Push(S,3);
	Push(S,4);
	Push(S,5);
	for(int i=0;i<=S.top;i++)
		printf("%d",S.data[i]);
	int x;
	Pop(S,x);
	printf("\n%d",x);
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章