C数据结构之顺序栈(数组实现2)

接着上面继续阐述c的数据结构之顺序栈(数组实现2),与上面不同的是,这种栈,虽名为栈,但实质是在堆区实现的栈,本质上是栈,只不过是在堆区实现的。这样做是为了节省程序本身的栈区空间,在更大的堆区来实现具体的程序。当一个项目代码大道几万行,甚至几百万行的时候,就显得尤为重要了,下面用c语言的模块化编程思想来实现:
/***主程序实现***/
#include "stack.h"

#define N 10
int main()
{
SqStack *stack = NULL;
int index;

stack = creat_stack(N);

for(index = 0;index < N;index ++)
push_stack(stack,index + 1);

for(index = 0;index < N;index ++)
printf("%-4d",pop_stack(stack));

putchar('\n');

free_stack(stack);

return 0;
}

--------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------

/***栈相关函数操作***/
#include "stack.h"

SqStack *creat_stack(int size)
{
SqStack *stack = NULL;
stack = (SqStack *)malloc(sizeof(SqStack));
stack->data = (datatype *)malloc(sizeof(datatype) * size);
stack->top = -1;//point to the read area !
stack->size = size;

return stack;
}


int isfull_stack(SqStack *stack)
{
return stack->top >= stack->size - 1;
}

int isempty_stack(SqStack *stack)
{
return stack->top < 0;
}

int push_stack(SqStack *stack,datatype value)
{
if(isfull_stack(stack))
return -1;

stack->data[++stack->top] = value;

return 0;
}


datatype pop_stack(SqStack *stack)
{
if(isempty_stack(stack))
return -1;

return stack->data[stack->top--];
}

int free_stack(SqStack *stack)
{
free(stack->data);
free(stack);

return 0;
}
------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------

/***栈相关函数的头文件***/
#ifndef _STACK_H_
#define _STACK_H_


#include <stdio.h>
#include <stdlib.h>


/**stack datatype !**/
typedef int datatype;

typedef  struct _stack_
{
datatype *data;
int top;
int size;
}SqStack;


/**stack statement area !**/
SqStack *creat_stack(int size);
int isfull_stack(SqStack *stack);
int isempty_stack(SqStack *stack);
int push_stack(SqStack *stack,datatype value);
datatype pop_stack(SqStack *stack);
int free_stack(SqStack *stack);

#endif

程序运行结果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值