本文目錄一覽:
- 1、關於C語言堆棧的問題!
- 2、C語言程序棧堆的問題
- 3、C語言中堆棧問題
關於C語言堆棧的問題!
C語言中堆棧說的是數據結構,和系統中的堆棧中是不一樣的,/*
**用一個靜態數組實現的堆棧。數組的長度只能通過修改#define的定義
**並對模塊重新進行編譯
*/#include”stack.h”
#includeassert.h#define STACK_SIZE 100 /*堆棧中值數量的最大限制*//*
**存儲堆棧中值的數組和一個指向堆棧頂部元素的指針
*/
static STACK_TYPE stack[STACK_SIZE];
static int top_element =-1;/*push*/
void push(STACK_TYPE value)
{
assert(!is_full());
top_element +=1;
stack[top_element]=value;
}/*pop*/
STACK_TYPE pop(void)
{
STACK_TYPE temp;
assert(!is_empty());
temp=stack[top_element];
top_element -= 1;
return temp;
}/*top*/
STACK_TYPE top (void)
{
assert(!is_empty());
return stack[top_element];
}/*
** is _empty
*/
int is_empty(void)
{
return top_element == -1;
}/*
**is_full
*/
int is_full(void)
{
return top_element ==STACK_SIZE -1;
}這是個靜態堆棧,你可以動態的申請內存來編寫動態堆棧
C語言程序棧堆的問題
你在棧中使用了過多空間(例如開闢了超大數組)。將佔用過多空間的變量移到全局區或者使用malloc為其在堆中分配內存。
C語言中堆棧問題
我幫你寫了InitStack和StackEmpty函數,程序最終結果如下:
#define maxnum 20
#includestdio.h
#includestdlib.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
原創文章,作者:FIAC,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/137188.html