编写函数实现顺序栈的初始化、出栈、入栈运算。
函数接口定义:
在这里描述函数接口。例如:
Status iniStack(Sqstack &S); //初始化栈
Status push(Sqstack &S,SElemType x);//入栈
Status pop(Sqstack &S,SElemType &e);//出栈
裁判测试程序样例:
#include <stdio.h>
#include <malloc.h>
typedef int Status;
typedef char SElemType;
#define stack_INIT_SIZE 100
#define stackINCREMENT 10
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef struct {
SElemType *base; //栈底指针
SElemType *top; //栈顶指针
int stacksize; //栈空间
}Sqstack;
Status iniStack(Sqstack &S) //初始化栈
{
/* 请在这里填写答案 */
}//InitStack
Status push(Sqstack &S,SElemType x)
{
/* 请在这里填写答案 */
}
Status pop(Sqstack &S,SElemType &e)
{
/* 请在这里填写答案 */
}
Status print_stack(Sqstack S)//打印栈中元素
{
SElemType *p=S.base;
while(p<S.top)
{
printf("%c ",*p);
p++;
}
return OK;
}
int main()
{
Sqstack S;
SElemType k;
int n,i;
iniStack(S);
SElemType e;
scanf("%c",&e);
while(e!='0') //不断输入入栈元素,直到字符‘0’weizhi
{ if(push(S,e)==ERROR)
printf("入栈失败!\n");
scanf("%c",&e);
}
scanf("%d",&n); //输入出栈次数
for(i=1;i<=n;i++)
if(pop(S,k)==ERROR)
printf("出栈失败!\n");
else
printf("出栈元素为:%c\n",k);
print_stack(S); //打印出栈后栈中元素
return 0;
}
return 0; }
输入样例:
ABCD0
2
输出样例:
出栈元素为:D
出栈元素为:C
A B
代码如下:
Status iniStack(Sqstack &S){
S.base = (char *)malloc(stack_INIT_SIZE*sizeof(char));
if(S.base ==0){
return 0;
}
S.top = S.base;
S.stacksize =stack_INIT_SIZE;
}
Status push(Sqstack &S,char x)
{
/* 请在这里填写答案 */
if(S.top-S.base==S.stacksize) return 0;
*S.top++=x;
return 1;
}
Status pop(Sqstack &S,char &e)
{
/* 请在这里填写答案 */
if(S.top==S.base) return 0;
e=*--S.top;
return e;
}