12.27用链表实现简单的堆栈操作

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;
}

结果如下:
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值