C 堆栈的链式表示

题目:用没有头节点的单链表来表示堆栈,功能执行效率比线性表更高,入栈与出栈操作都通过头插入和头删除实现

程序:

#include<stdio.h>
#include<stdlib.h>
#define MAX 10


typedef struct linkedstack
{
int num;
struct linkedstack *next;
}LinkedStack;
typedef LinkedStack * Link;


enum return_result{EMPTY_OK=10000,EMPTY_NO,PUSH_OK,PUSH_NO,
POP_NO,POP_OK,FULL_NO,FULL_OK};


void create_empty_stack(Link * top);
void is_malloc_ok(Link new_stack);
void create_newstack(Link * new_stack);
int  count(Link top);
int  is_empty(Link top);
int  is_full(Link top);
int push(Link *top,Link new_stack,int num);
int pop(Link *top);
int get(Link top);


int main()
{
Link top = NULL;
Link new_stack = NULL;
create_empty_stack(&top);
int i;
for (i = 0; i < MAX; i++)
{
create_newstack(&new_stack);
push(&top, new_stack, i + 1);
printf("count = %d\n", count(top));
}
for (i = 0; i < MAX; i++)
{
printf("num = %d\n",get(top));
pop(&top);
}
return 0;
}


void create_empty_stack(Link * top)
{
*top = NULL;
}


void create_newstack(Link * new_stack)
{
*new_stack = (Link)malloc(sizeof(LinkedStack));
is_malloc_ok(*new_stack);
}


void is_malloc_ok(Link new_stack)
{
if (new_stack == NULL)
{
printf("malloc error!\n");
exit(-1);
}
}


int  count(Link top)
{
Link p;
int num;
p = top;
num = 0;
while (p != NULL)
{
p = p->next;
num++;
}
return num;
}


int  is_empty(Link top)
{
if (top == NULL)
{
return EMPTY_OK;
}
return EMPTY_NO;
}


int  is_full(Link top)
{
if (count(top)>=MAX)
{
return FULL_OK;
}
return FULL_NO;
}


int push(Link * top, Link new_stack, int num)
{
if (is_full(*top) == FULL_NO)
{
new_stack->next = *top;
*top = new_stack;
new_stack->num = num;
return PUSH_OK;
}
printf("the stack is full!\n");
return PUSH_NO;
}


int pop(Link * top)
{
Link p;
p = *top;
int num;
if (is_empty(*top) == EMPTY_NO)
{
num = p->num;
*top = (*top)->next;
free(p);
return num;
}
printf("the stack is empty!\n");
return POP_NO;
}


int get(Link top)
{
int num;
if (is_empty(top) == EMPTY_NO)
{
num = (top)->num;
return num;
}
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值