编写一个C源程序,其中包含顺序表示的空栈的创建、判断栈是否为空、进栈、出栈、取栈顶元素等操作。

如题所述

楼主你好
以下是顺序栈的操作实现(c语言代码):

#include<stdio.h>
#include<malloc.h>
#define MAX 20

typedef struct node
{
int data[MAX];
int top;
}Stack;

void Initial_Stack(Stack * &s)//初始化栈
{
s=(Stack *)malloc(sizeof(Stack));
s->top=-1;
}

void Empty_Stack(Stack *s)//判断栈是否为空
{
if(-1 == s->top)
printf("栈空!\n");
else
printf("栈非空!\n");
}

void Creat_Stack(Stack * &s)//创建栈
{
int i=0;

printf("Enter the data:\n");
do{
scanf("%d",s->data+i);
s->top=i;
i++;
}while(i<MAX&&getchar()!='\n');
}

void Disp_Stack(Stack * &s)//打印栈
{
int i;
for(i=s->top;i>=0;i--)
printf("%d: %d\n",s->top-i+1,s->data[i]);
}

void Push_Stack(Stack * &s,int e)//压栈
{
if(s->top==MAX-1)
{
printf("Stack full!\n");
return;
}

s->top++;
s->data[s->top]=e;
printf("After push:\n");
Disp_Stack(s);
}

void Pop_Stack(Stack * &s)//出栈
{
if(s->top==-1)
{
printf("Stack empty!\n");
return;
}
s->top--;

printf("After pop:\n");
Disp_Stack(s);
}

int main()
{
Stack *S;

Initial_Stack(S);
Empty_Stack(S);
Creat_Stack(S);
Empty_Stack(S);
printf("Initial stack:\n");
Disp_Stack(S);
Push_Stack(S,0);
Pop_Stack(S);

return 0;
}

希望能帮助你哈
温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-04-13

1,如何断栈是否为空:

C# 中 Stack 类的Count 属性 返回就是堆栈的长度。

System.Collections.Stack stack = new System.Collections.Stack();

stack.push( "1" );

if( 0==stack.Count )

MessageBox.Show("堆栈为空。");

else

MessageBox.Show("堆栈为空。");

2,判断栈满、进栈的语句:

int stackfull(seqstack*s)

{

return (s->top==stacksize-1);

}

stacksizes=栈大小,栈从0开始,当栈顶指针=栈大小-1时,说明栈已经存满了

void push(seqstack *s,datatype x)

{

if(stackfull(s))

error("stack verflow");  如果出错,进入出错处理,不进行下一步

s->data[++s->top]=x;   栈顶指针先加1,然后再将x保存到栈顶位置

本回答被网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网