链式栈

环境:gcc

目的:链式栈练习

功能:

1. 创建栈

2 . 入栈

3. 出栈

 

/*************************************************************************

 @Author: wanghao

 @Created Time : Wed 09 May 2018 10:42:01 PMPDT

 @File Name: linklist.c

 @Description:

 ************************************************************************/

#include <stdio.h>

#include <stdlib.h>

 

typedef int data_t;

 

typedef struct stack_t

{

       data_t data;

       struct stack_t *pnext;

}Stack;

 

Stack *create_stack(void)

{

       Stack*node = NULL;

 

       node = (Stack *)malloc(sizeof(Stack));

       if(!node)

       {

              printf("Malloc node fail!\n");

              return NULL;

       }

 

       node->data = 0;

       node->pnext = NULL;

 

       return node;

}

 

int empty_stack(Stack *stack)

{

       if(!stack)

       {

              printf("Stackdoes not exist!\n");

              return -1;

       }

 

       return stack->pnext == NULL ? 1 : 0;

 

}

 

int push_stack(Stack *stack, data_t data)

{

       Stack*newnode = NULL;

 

       if(!stack)

       {

              printf("Stackdoes not exist!\n");

              return -1;

       }

 

       newnode = create_stack();

       if(!newnode)

       {

              printf("Createstack fail!\n");

              return 0;

       }

 

       newnode->data= data;

       newnode->pnext = stack->pnext;

       stack->pnext = newnode;

 

       return 1;

 

}

 

int pop_stack(Stack *stack, data_t *data)

{

       Stack *node = NULL;

 

       if(!stack)

       {

              printf("Stackdoes not exist!\n");

              return -1;

       }

 

       if(empty_stack(stack))

       {

              printf("Stackis empty!\n");

              return 0;

       }

 

       node = stack->pnext;

       stack->pnext= node->pnext;

      

       *data = node->data;

       free(node);

       node = NULL;

 

       return 1;

}

 

int main(int argc, const char *argv[])

{

       int i;

       data_t data;

       Stack *stack = NULL;

 

       stack = create_stack();

       if(!stack)

       {

              printf("Createstack fail!\n");

              return -1;

       }

 

       for(i= 0; i < 5; i++)

       {

              push_stack(stack,i+1);

       }

 

       for(i= 0; i < 6; i++)

       {

              pop_stack(stack,&data);

              printf("%d\t",data);

       }

       printf("\n");

 

       return 0;

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值