
#define M 100
typedef struct
{
int elem[M]
int top
}SqStack
void init(SqStack*s)/*初始化栈*/
{s->top=0}
int empty(SqStack*s) /*栈为空返回1,否则返回0 */
{return(! s->top)} //第一处
int push(SqStack*s,int x) /*进栈*/
{if(s->top==M)return 0
s->elem[s->top]=x //第二处
s->top++ //第三处
return 1
}
int pop(SqStack*s,int *y) /*出栈*/
{if(s->top==0)return 0
--s->top*y=s->elem[s->top]
return 1
}
void main()
{
int temp
int x,h,*y=&temp //注意这里,这个题目本来这里是错的
SqStack stack
SqStack *a=&stack //注意这里,这个题目察猛本来这里是错的
init(a)
scanf("丛则%d%d",&x,&h)
while(x!=0)
{push(a,x%h) //第四处
x=x/h}
printf("\n")
while(!empty(a))
{pop(a,y) //第五败郑桥处
if(*y<10)
printf("%d",*y)
else
printf("%c",*y-10+97)
}
}
一般情况下,初始设置top=-1,栈空条件:top==-1,栈满条件:top==length-1,栈长top+1,top==N(即length)表示栈空,故栈长top-1,栈满条件:top==N-N=0 。
因为用一个长度为n的数组顺序储存一个栈 然而数组是从0~n-1 栈空为top==n 那么栈满为top==1。t数组长度固定为n,则可存储n个元素,top=n表示栈空,向栈中插入一个元素后,top-1=n-1,n个元素存储完了就满栈了,top的值就等于0了。
扩展资料:
栈在程序的运行中有着举足轻重的作用。最重要的是栈保存了一个函数调用时所需要的维护信息,这常常称之为堆栈帧或者活动记录。
允许进行插入和删除 *** 作的一端称为栈顶(top),另一芹庆端为栈底(bottom);栈底固定,而栈顶浮动;栈中元素个数为零时称为空栈。插入一般称神纯为进栈(PUSH),删除则称为退栈(POP)。栈也称为先进后出表。
参考资料来源:百度游首咐百科-栈
#include<stdlib.h>typedef struct node
{
int num
struct node *next
}*link,LINK
void empty(link top)
{
top=NULL
}
int pd(link top)
{
if(top==NULL)
{
return 0
}
else
{
return 1
}
}
link create(link top,int n)
{
link s
s=(link)malloc(sizeof(LINK))//分配时要分配一个结构体的空间,而不是仅仅一个指针的空间。
s->num=n
s->next=top
top=s
return top
}
/*如上个函数,要返回蚂让一个指针,否则是不能改变top的值的。因为在函数中只能修改指针指向地址的内容,而它指向的地址是不会改变的。因此要想使指针指向的地址发生变化,要重新返回一个link。出栈的数据放到x中。*/
link outword(link top,int *x)
{
link p
if(pd(top)==0)
{
printf("underflow")
return top
}
else
{
p=top
*x=top->num
top=top->next
free(p)
return top
}
}
void main()
{
link top=NULL
int n,*x=(int*)malloc(sizeof(int))
//top=(link)malloc(sizeof(LINK))
//empty(top)
printf("进栈\n")
scanf("%d",&n)
//top->num=n
while(n!=-1)
{
top=create(top,n)
scanf("%d",&n)
}
printf("出栈\n")
while(pd(top)!=NULL)
{
top=outword(top,x)
printf("%d\n",*x)
}
}
已经可以运行。主要问题就是出栈函数的问题,需御物镇要你仔细考虑一下镇粗。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)