堆栈的相关操作

说明:本代码主要是实现了堆栈的进栈和出栈,还有堆栈的逆序操作。

 #include "stdio.h"
  2 #include "malloc.h"
  3 #define STACK_NUM 20
  4 struct Stack_Node;
  5 typedef struct Stack_Node
  6 {
  7     int data;
  8     struct Stack_Node *next;
  9 }StackNode;
 10 
 11 
 12 //define the fist stack node
 13 static StackNode *stack_head = NULL;
 14 void pop(void)
 15 {
 16     StackNode *old_head = NULL;
 17     old_head = stack_head;
 18     stack_head = stack_head->next;
 19     free(old_head);
 20 }
 21 
 22 void push(int data)
 23 {
 24     StackNode *new_node = NULL;
 25     new_node = (StackNode *)malloc(sizeof(StackNode));
 26     if(new_node == NULL)
 27         printf("malloc for new node fail.\n");
 28 
 29     new_node->data = data;
 30     new_node->next = stack_head;
 31     stack_head = new_node;
 32 }
 33 
 34 void print_stack()
 35 {
 36     StackNode *node = NULL;
 37     node = stack_head;
 38     while(node != NULL){
 39         printf("%d ",node->data);
 40         node = node->next;
 41     }
 42     printf("\n");
 43 }
 44 
 45 void reverse_stack(void)
 46 {
 47     StackNode *pCurr = NULL;
 48     StackNode *pNext = NULL;
 49     pCurr = stack_head->next;
 50     stack_head->next = NULL;
 51     while(pCurr != NULL){
 52         pNext = pCurr->next;
 53         pCurr->next = stack_head;
 54         stack_head = pCurr;
 55         pCurr = pNext;
 56     }
 57 }
 58 void main(void)
 59 {
 60     printf("to create the stack.\n");
 61     int i;
 62     for( i = 1;i <=STACK_NUM;i++){
 63         push(i);
 64     }
 65     printf("--------print the original stack-------\n");
 66     print_stack();
 67     pop();
 68     pop();
 69     printf("--------print the stack after pop twice-------\n");
 70     print_stack();
 71     printf("--------print the stack after reverse it -------\n");
 72     reverse_stack();
 73     print_stack();
 74     return;
 75 }

执行结果:

kldong@ubuntu:~/learning/linux/stack/own$ ./run 
to create the stack.
--------print the original stack-------
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 
--------print the stack after pop twice-------
18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 
--------print the stack after reverse it -------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值