链表实现堆栈

list_stack.h

#define STACK_TYPE char

 

void destroy_stack();

 

void push(STACK_TYPE a);

void pop();

STACK_TYPE top();

 

int is_empty();

 

list_stack.c

#include "list_stack.h"

#include <stdlib.h>

#include <assert.h>

#include <malloc.h>

 

typedef struct node

{

       STACK_TYPE data;

       struct node *pnext;

}N_TYPE;

 

static N_TYPE *ptop = NULL;

 

 

void destroy_stack()

{

       N_TYPE *ptemp;

      

       if(!is_empty())

       {

              if(ptop->pnext == NULL)

              {

                     free(ptop);

              }

              else

              {

                     ptemp = ptop->pnext;

                    

                     for(;ptemp->pnext != NULL; ptemp = ptop->pnext)

                     {

                            free(ptop);

                            ptop = ptemp;

                     }

                     free(ptemp);

                     ptemp = NULL;

              }

              ptop = NULL;

       }

}

 

void push(STACK_TYPE a)

{

       N_TYPE *ptemp;

      

       if(is_empty())

       {

              if((ptop = (N_TYPE *)malloc(sizeof(N_TYPE))) == NULL)

              {

                     perror("malloc: ");

                     exit(1);

              }

              ptop->pnext = NULL;

       }

       else

       {

              ptemp = (N_TYPE *)malloc(sizeof(N_TYPE));

              if(ptemp == NULL)

              {

                     perror("malloc: ");

                     exit(1);

              }

             

              ptemp->pnext = ptop;

              ptop = ptemp;

       }

       ptop->data = a;

}

 

void pop()

{

       N_TYPE *ptemp;

      

       assert(!is_empty());

      

       if(ptop->pnext == NULL)

       {

              free(ptop);

             

              ptop = NULL;

       }

       else

       {

              ptemp = ptop;

              ptop = ptop->pnext;

             

              free(ptemp);

              ptemp = NULL;

       }

}

 

STACK_TYPE top()

{

       assert(!is_empty());

      

       return ptop->data;

}

 

int is_empty()

{

       return ptop == NULL;

}

 

test.c

#include "list_stack.h"

#include <stdio.h>

 

void main()

{

       push('a');

       push('b');

       push('c');

       push('d');

       push('e');

      

       pop();

       pop();

      

       printf("top = %c/n", top());

      

       destroy_stack();

 

       push('a');

       push('d');

       push('3');

       pop();

       printf("top = %c/n", top());

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值