题目:用没有头节点的单链表来表示堆栈,功能执行效率比线性表更高,入栈与出栈操作都通过头插入和头删除实现
程序:
#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;
}