1. 程式人生 > >棧的基本操作 出棧與入棧

棧的基本操作 出棧與入棧

article 安全 empty scan -s type fine mod pos

#include<stdio.h>
#include<stdlib.h>
#define LENGTH 100	//初始分配棧的長度
#define ADD_LEN 10	//棧長增量
typedef struct 
{//構造棧的數據類型 
	int *base;
	int *top;
	int stacksize;
}SqStack;
void CreateStack(SqStack &S);//初始化一個棧
void PushStack(SqStack &S,int e);//e進棧
void PopStack(SqStack &S);//棧頂元素出棧
void DestroyStack(SqStack &S);//銷毀棧
void PrintfStack(SqStack &S);//輸出當前的棧
void main()
{	SqStack Sa;
	int m,n;
	CreateStack(Sa);
	printf("Please input the total of inserting number:");
	scanf("%d",&m);
	while(m>LENGTH)
	{	printf("The number you input can't be larger than %d,please input again:\n",LENGTH);
		scanf("%d",&m);
	}
	while(m--)
	{	printf("Please input a number to insert:");
		scanf("%d",&n);
		PushStack(Sa,n);
	}
	PrintfStack(Sa);
	PopStack(Sa);
	PrintfStack(Sa);
	DestroyStack(Sa);
}
void CreateStack(SqStack &S)
{	S.base=(int *)malloc(LENGTH*sizeof(int));
	if(!S.base)
	{	printf("Fail to create stack!\n");
		return;
	}
	S.top=S.base;
	S.stacksize=LENGTH;
	printf("Success to create stack!\n");
}
void PushStack(SqStack &S,int e)
{	if(S.top-S.base>=S.stacksize)//考慮棧是否已滿,如滿。則從新分配空間
	{	S.base=(int *)realloc(S.base,(S.stacksize+ADD_LEN)*sizeof(int));
		if(!S.base)
			return;
		S.top=S.base+S.stacksize;
		S.stacksize+=ADD_LEN;
	}
	*S.top++=e;
	printf("%d success to insert the stack!\n",e);
} 
void PopStack(SqStack &S)
{	int m;
	if(S.top==S.base)
	{	printf("The stack is empty!\n");
		return;
	}
	m=*--S.top;
	printf("%d is out of the stack!\n",m);
}
void DestroyStack(SqStack &S)
{	free(S.base);//釋放空間
	S.base=NULL;
	*S.top=-1;//將其它成員設置成安全值
	S.stacksize=0;
	printf("Success to destroy the stack!\n");
}
void PrintfStack(SqStack &S)
{	int *p;
	p=S.top;
	printf("The stack is :");
	while(--p>=S.base)
		printf("%d",*p);
	printf("\n");
}

棧的基本操作 出棧與入棧