6.题目:利用链表实现一个先入后出的栈结构,并提供栈操作的push和pop的接口
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
#define MAN_ERR 0
#define MAN_OK 1
struct node
{
int num;
struct node *next;
struct node *prior;
};
typedef struct node Node;
typedef struct node * link;
enum return_result{FULL_OK,FULL_NO,EMPTY_OK,EMPTY_NO,PUSH_OK,PUSH_NO,POP_OK,POP_NO};
void create_stack(link * stack)
{
*stack = (link)malloc(sizeof(Node));
(*stack)->next = (*stack)->prior = *stack;
}
int is_malloc_ok(link new_node)
{
if(new_node == NULL)
{
printf("malloc error!\n");
return MAN_ERR;
}
else
{
return MAN_OK;
}
}
void create_node(link * new_node)
{
*new_node = (link)malloc(sizeof(Node));
while(is_malloc_ok(*new_node) == 0)
{
*new_node = (link)malloc(sizeof(Node));
}
}
void insert_stack_tail(link stack, link new_node)
{
link p;
p = stack;
while(p->next != stack)
{
p = p->next;
}
p->next = new_node;
new_node->next = stack;
new_node->prior = p;
stack->prior = new_node;
}
int is_full(link stack)
{
if(stack->prior->num == MAX)
{
return FULL_OK;
}
else
{
return FULL_NO;
}
}
int push_stack(link stack,link new_node,int i)
{
if(is_full(stack) == FULL_OK)
{
printf("stack is full!\n");
return PUSH_NO;
}
new_node->num = i;
return PUSH_OK;
}
int is_empty(link stack)
{
if(stack->prior->num == MAN_ERR)
{
return EMPTY_OK;
}
return EMPTY_NO;
}
int pop_stack(link stack)
{
if(is_empty(stack) == EMPTY_OK)
{
printf("stack is empty!\n");
return POP_NO;
}
return POP_OK;
}
int main()
{
link stack = NULL;
link new_node = NULL;
int i;
create_stack(&stack);
for(i=0;i<10;i++)
{
create_node(&new_node);
insert_stack_tail(stack,new_node);
if(push_stack(stack,new_node,i+1) == PUSH_OK)
{
printf("%-5d",new_node->num);
printf("push ok %d!\n",new_node->num);
}
}
/*printf("%d\n",stack->num);
printf("%d\n",stack->prior->num);
printf("%d\n",stack->prior->prior->num);
printf("%d\n",stack->next->num);*/
printf("\n\n");
for(i=MAX-1;i>=0;i--)
{
if(pop_stack(stack) == POP_OK)
{
printf("%-5d",stack->prior->num);
printf("pop ok %d!\n",stack->prior->num);
stack = stack->prior;
}
}
free(stack);
return 0;
}
结果如下: