栈的基本操作

时间:2025-03-14 08:16:36


#include ""
#include<cstdio>
#include<cstdlib>
#define OK 1
#define TRUE 1
#define ERROR 0
#define FALSE 0
#define overflow -2
#define STACK_INTT_SIZE 100
#define STACK_INIT_INCREMENT 20
#define Status int
#define ElemType int
typedef struct 
{
	ElemType *base,*top;
	int stackSize;
}SqStack;
/*   栈的操作 
   Status InitStatck(SqStack &s)   初始化栈 
   Status DestoryStatck(SqStack &s)  销毁栈 
   Status ClearStack(SqStack &s)    清除栈 
   bool StackEmpty(SqStack s)         栈是否为空 
   int StackLength(SqStack s)        栈的长度 
   Status GetTop(SqStack s,SElemType &e)  得到栈顶 
   Status Push(SqStack &s,SElemType e)   压栈 
   Status Pop(SqStack &s,SElemType &e)   出栈
   void DisplayStack(SqStack s);    显示栈内的元素
   */
Status InitStatck(SqStack &s)
{
	=(ElemType*)malloc(STACK_INTT_SIZE*(sizeof(ElemType)));
	if(!)
		return ERROR;
	else
		=;
	=STACK_INTT_SIZE;
}
Status DestoryStatck(SqStack &s)
{
	=;
	free();
	=NULL;
	=NULL;
	 return OK;  
}
bool StackEmpty(SqStack s)
{
	if(==)   
	  return TRUE;   
	 else    
	  return FALSE;    
}
int StackLength(SqStack s)  
{
	if(=)    
	  return ERROR;   
	 else    
	  return ();  
}
Status GetTop(SqStack s,ElemType &e)
{
	if(StackEmpty(s))
	{
		printf("This stack is empty.");
		return ERROR;
	}
	else
	{
		--;
		e=*;
		return OK;
	}
}
Status Push(SqStack &s,ElemType e)
{
	if(StackLength(s)==STACK_INTT_SIZE)
	{
		ElemType*temp=(ElemType*)realloc(,(STACK_INTT_SIZE+STACK_INIT_INCREMENT)*(sizeof(ElemType)));
		if(!temp)
			return ERROR;
		=temp;
		=+STACK_INTT_SIZE;
		=STACK_INTT_SIZE+STACK_INIT_INCREMENT;
		*(++)=e;
		return OK;
	}
	else
	{
		*=e;
		++;
		return OK;
	}
}
Status Pop(SqStack &s,ElemType &e)
{
	if(StackEmpty(s))
	{
		printf("This stack is empty.");
		return ERROR;
	}
	else
	{
		e=*(--);
		return OK;
	}
}
Status ClearStack(SqStack &s)
{
	=;
	=0;
	 return OK;  
}
void DisplayStack(SqStack s)
{
	if(StackEmpty(s))
		exit(-1);
	while(!=)
		printf("%d\n",*(--));
}
int _tmain(int argc, _TCHAR* argv[])
{
	SqStack statck;  
	InitStatck(statck);  
	for(int i=0;i<5;i++)  
	 {  
		  if(Push(statck,i))  
		      printf("%d is push in this statck success!\n",i);  
		  else   
		     printf("/n/thappen a error\n\t");  
	 }  
	DisplayStack(statck);//显示栈内的元素
	int tem;  
    printf("now  i will print this top of statck !\n");  
    GetTop(statck,tem);  
    printf("%d is top of this statck\n",tem);  

	DestoryStatck(statck);

	system("pause");
	return 0;
}