亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

請教下判斷棧為空的函數怎么寫?

請教下判斷棧為空的函數怎么寫?

C PHP
呼如林 2022-08-12 14:10:25
#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;elses->top++;s->stack[s->top]=x;return true;}int pop(struct stacktype *s){if(s->top <0)return NULL;elses->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 回答

?
溫溫醬

TA貢獻1752條經驗 獲得超4個贊

我幫你寫了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


查看完整回答
反對 回復 2022-08-15
  • 1 回答
  • 0 關注
  • 394 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號