1. 程式人生 > >C語言實現順序棧的初始化&進棧&出棧&讀取棧頂元素

C語言實現順序棧的初始化&進棧&出棧&讀取棧頂元素

/*順序表實現棧的一系列操作*/ 

#include<stdio.h>
#include<stdlib.h> 

#define Stack_Size 50             //設棧中元素個數為50 
#define OK 1
#define ERROR 0

typedef struct                
{
	int elem[Stack_Size];          //用來存放棧中元素的一維陣列 
	int top;	                   //用來存放棧頂元素的下標,top為 -1 表示空棧 
}SeqStack;

/**********************各個子函式的定義*********************/
int initStack(SeqStack *S);     	//初始化順序棧 
void push(SeqStack *S,int n);  		//順序棧進棧運算 
void pop(SeqStack *S);				//順序棧出棧運算 
int getTop(SeqStack *S,int *s);     //讀取棧頂元素 
 
int main()
{
	SeqStack *S;
	int choice;
	while(true)
	{
        printf("*****************Please enter your choice*****************\n\n");
        printf("                choice 1:Stack initialization\n");
        printf("                choice 2:Into the stack\n");
        printf("                choice 3:Out of the stack\n");
        printf("                choice 4:Read the stack elements\n");
        printf("                choice 0:exit\n\n");
	 	scanf("%d",&choice);
		switch(choice)
		{
			case 1:
				(initStack(S)==1)?printf("initStck success.\n"):printf("initStack ERROR\n");
				break;
			case 2:
				int n;
				printf("Please enter the number into the stack elements:");
				scanf("%d",&n);
				push(S,n);
				break;
			case 3:
				pop(S);
				break;
			case 4:
				int* s;
				(getTop(S,s)==1)? printf("棧頂元素是:%d.\n",*s):printf("An empty stack error!!!!\n"); //三目運算子
				break;		
			case 0:
				exit(0);
				break;
			default:
				printf("ERROR!!\n");
				exit(0);
				break;
		}
	}
	return 0;
} 

/**********************各個子函式功能的實現*********************/
int initStack(SeqStack *S)    //初始化順序棧 
{	     
	if(S!=NULL)
	{
		S->top=-1;             //置為空棧 
		return OK;
	}
	else return ERROR;        //記憶體空間不足 
}
void push(SeqStack *S,int n)  //進棧 ,將元素壓入棧中 
{   
	int n1,n2;
	if(((S->top)+n)<=Stack_Size-1)   //壓入棧中的元素不能超過棧的最大儲存 
	{  
		printf("Please enter into the stack elements in turn:\n");  
		for(n1=0;n1<n;n1++)
		{
			scanf("%d",&n2);
			S->top++;                    //移動棧頂指標 
			S->elem[S->top]=n2;
		}
		printf("%d個元素依次進棧成功\n",n);
	}
	else
	{                    //棧空間不夠 
		printf("ERROR There is insufficient space on the stack.\n");            
	}                 
}
void pop(SeqStack *S)
{     //棧頂元素出棧 
	int a;
	if(S->top==-1)
	{               //棧為空,操作失敗 
		printf("An empty stack error!!!!\n");
	}
	else
	{
		a=S->elem[S->top];
		S->top--;
		printf("棧頂元素%d出棧成功.\n",a);  //出棧成功 
	}  

}
int getTop(SeqStack *S,int *s)   //獲取棧頂元素 
{    
	if(S->top==-1)
	{               //棧為空,操作失敗 
		return ERROR;
	}
	else
	{
		*s=S->elem[S->top];   //讀取棧頂元素成功 
		return OK;
	}
}