首页 > 编程知识 正文

c语言经典堆栈问题,C语言堆和栈

时间:2024-04-24 11:43:04 阅读:333696 作者:CEWM

本文目录一览:

关于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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。