C语言中堆栈问题
#definemaxnum20#include<stdio.h>#include<stdlib.h>structstacktype{intstack[maxnum];in...
#define maxnum 20
#include<stdio.h>
#include<stdlib.h>
struct stacktype
{
int stack[maxnum];
int top;
};
int push(struct stacktype *s,int x)
{
if(s->top>=maxnum-1)
return false;
else
s->top++;
s->stack[s->top]=x;
return true;
}
int pop(struct stacktype *s)
{
if(s->top <0)
return NULL;
else
s->top--;
return(s->stack[s->top+1]);
}
dec_to_bin(int n,int b)
{
int e;
InitStack(S);//请问初始化堆栈函数怎么写?
while(n)
{
push(S,n%b);
n=n/b;
}
while(!StackEmpty)//判断栈为空的函数怎么写?
{
e=pop(S);
printf("%d",e);
}
}
main
{
dec_to_bin(13,2);
} 展开
#include<stdio.h>
#include<stdlib.h>
struct stacktype
{
int stack[maxnum];
int top;
};
int push(struct stacktype *s,int x)
{
if(s->top>=maxnum-1)
return false;
else
s->top++;
s->stack[s->top]=x;
return true;
}
int pop(struct stacktype *s)
{
if(s->top <0)
return NULL;
else
s->top--;
return(s->stack[s->top+1]);
}
dec_to_bin(int n,int b)
{
int e;
InitStack(S);//请问初始化堆栈函数怎么写?
while(n)
{
push(S,n%b);
n=n/b;
}
while(!StackEmpty)//判断栈为空的函数怎么写?
{
e=pop(S);
printf("%d",e);
}
}
main
{
dec_to_bin(13,2);
} 展开
1个回答
展开全部
我帮你写了InitStack和StackEmpty函数,程序最终结果如下:
#define maxnum 20
#include<stdio.h>
#include<stdlib.h>
struct stacktype
{
int stack[maxnum];
int top;
};
struct stacktype *S;//顶一个堆栈
int push(struct stacktype *s,int x)
{
if(s->top>=maxnum-1)
return false;
else
s->top++;
s->stack[s->top]=x;
return true;
}
int pop(struct stacktype *s)
{
if(s->top <0)
return NULL;
else
s->top--;
return(s->stack[s->top+1]);
}
//初始化堆栈
void InitStack(struct stacktype* &S)
{
S = (struct stacktype *)malloc(sizeof(struct stacktype));
S->top = -1;
}
//判断堆栈是否为空
bool StackEmpty(struct stacktype *S)
{
if (S->top <0)
{
return true;
}
return false;
}
void dec_to_bin(int n,int b)
{
int e;
InitStack(S);//请问初始化堆栈函数怎么写?
if (S ==NULL)
{
printf("error \n");
return;
}
while(n)
{
push(S,n%b);
n=n/b;
}
while(!StackEmpty(S))//判断栈为空的函数怎么写?
{
e=pop(S);
printf("%d",e);
}
}
void main()
{
dec_to_bin(13,2);
printf("\n");
}
程序运行结果为:
1101
#define maxnum 20
#include<stdio.h>
#include<stdlib.h>
struct stacktype
{
int stack[maxnum];
int top;
};
struct stacktype *S;//顶一个堆栈
int push(struct stacktype *s,int x)
{
if(s->top>=maxnum-1)
return false;
else
s->top++;
s->stack[s->top]=x;
return true;
}
int pop(struct stacktype *s)
{
if(s->top <0)
return NULL;
else
s->top--;
return(s->stack[s->top+1]);
}
//初始化堆栈
void InitStack(struct stacktype* &S)
{
S = (struct stacktype *)malloc(sizeof(struct stacktype));
S->top = -1;
}
//判断堆栈是否为空
bool StackEmpty(struct stacktype *S)
{
if (S->top <0)
{
return true;
}
return false;
}
void dec_to_bin(int n,int b)
{
int e;
InitStack(S);//请问初始化堆栈函数怎么写?
if (S ==NULL)
{
printf("error \n");
return;
}
while(n)
{
push(S,n%b);
n=n/b;
}
while(!StackEmpty(S))//判断栈为空的函数怎么写?
{
e=pop(S);
printf("%d",e);
}
}
void main()
{
dec_to_bin(13,2);
printf("\n");
}
程序运行结果为:
1101
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询