顺序栈的实现

/*顺序栈的实现*/
#include<stdio.h>
#define stacksize 50
#define TRUE 1
#define FALSE 0
typedef struct{
	char elem[stacksize];
	int top;
}sequencestack;

/*顺序栈的初始化*/
void initial(sequencestack * S)
{
	S->top=-1;//构造一个空栈
	printf("initial sequence-stack success!\n");
	fflush(stdout);
}

/*顺序栈进栈操作*/
int sequencepushstack(sequencestack *S)
{
	char c;
	int flag=1;
	if(S->top==stacksize-1)
	{
		printf("The stack is full !");
		fflush(stdout);
		return FALSE;
	}
	else
	{
		while(flag)
		{

		c=getchar();
		if(c!='$')
		{
			S->top++;
			S->elem[S->top]=c;
		}
		else
		{

		flag=0;
		printf("Stack success !\n");
		fflush(stdout);
		}
		}
	}
	return TRUE;

}
/*弹出栈顶元素*/
int sequencepopstack(sequencestack *S)
{
	if(S->top==-1)
	{
		printf("stack empty!\n");
	    fflush(stdout);
	}
	else
	{
		printf("The value of the stack top element is %c\n",S->elem[S->top]);
		fflush(stdout);
		S->top--;
	}
	return TRUE;
}
/*所有元素出栈*/
int popallelement(sequencestack *S)
{
	if(S->top==-1)
		{
			printf("\n stack empty!\n");
		    fflush(stdout);
		    return TRUE;
		}
	else
	{
	    printf("%2c",S->elem[S->top]);
	    fflush(stdout);
		S->top--;
		popallelement(S);
	}
	return FALSE;
}


int main(void)
{
	sequencestack *S;
	/*形参的星号是指指针,就是结构体类型的指针,函数形参是一个结构体指针,
	 * 实参也需要一个该结构体类型的指针,也就是要实参是一个地址传给形参
	 * 故在函数调用是使用的是&符号,就是区地址,将结构体变量的地址传过去
	 * 这样在函数里对于形参的修改就是对实参结构体变量的修改。*/
	initial(&S);
	printf("Please input the element to enter the stack and end with $ \n");
	fflush(stdout);
	sequencepushstack(&S);
	sequencepopstack(&S);
	printf("The out-of-stack elements are as follows...  \n");
	fflush(stdout);
	popallelement(&S);
	return 0;
}

调试结果

initial sequence-stack success!
Please input the element to enter the stack and end with $ 
edrftgyhujikol123456plmjkn$
Stack success !
The value of the stack top element is n
The out-of-stack elements are as follows...  
 k j m l p 6 5 4 3 2 1 l o k i j u h y g t f r d e
 stack empty!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值