Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7512634
  • 博文数量: 961
  • 博客积分: 15795
  • 博客等级: 上将
  • 技术积分: 16612
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-07 14:23
文章分类

全部博文(961)

文章存档

2016年(1)

2015年(61)

2014年(41)

2013年(51)

2012年(235)

2011年(391)

2010年(181)

分类: C/C++

2011-03-26 18:02:00

  1. /***********************************************
  2. * 文件名:
  3. * 功能:栈的简单应用
  4. * 说明:以链表作为存储结构,实现从键盘输入一组数据
  5.             然后按相反的次序输出
  6. * 时间:2011-3-26                --Lzy
  7. /***********************************************/

  8. #include <stdlib.h>
  9. #include <stdio.h>

  10. typedef struct node             /*结点类型定义*/
  11. {
  12.     int data;
  13.     struct node *next;            /*指向后继元素的指针域*/
  14. }Stack;

  15. void Stackinit(Stack *top)        /*栈初始化函数*/
  16. {
  17.     top->next = NULL;            /*栈顶置空*/
  18. }

  19. int Push(Stack *top, int X)        /*进栈*/
  20. {
  21.     Stack *P;
  22.     P = (Stack *)malloc(sizeof(Stack));        /*为节点分配空间*/    
  23.     P->data = X;    
  24.     P->next = top->next;        
  25.     top->next = P;                /*栈顶指针后移*/    
  26.     return 1;
  27. }

  28. int IsEmpty(Stack *top)            /*检查栈是否为空*/
  29. {
  30.     if(!top)        /*栈顶指针指向空*/
  31.         return 0;
  32.     return 1;
  33. }

  34. int Pop(Stack *top, int *ch)        /*出栈*/
  35. {    
  36.     Stack *P;
  37. //    P = (Stack *)malloc(sizeof(Stack));

  38.     P = top->next;
  39.     
  40.     if(IsEmpty(P) == 0)            /*栈为空*/
  41.         return 0;
  42.     
  43.     *ch = P->data;                /*弹出数据*/
  44.     top->next = P->next;        /*栈顶指针前移*/    
  45.     
  46.     free(P);
  47.     return 1;    
  48. }

  49. int main(void)
  50. {
  51.     int ch = 1;
  52.     Stack *top = (Stack *)malloc(sizeof(Stack));    
  53.     Stackinit(top);                /*栈初始化*/    
  54.     
  55.     while(ch != 0)
  56.     {
  57.         printf("请输入数据以0结束\n");    
  58.         scanf("%d",&ch);
  59.         if(ch == 0)
  60.             break;
  61.         Push(top, ch);            /*数据压入栈中*/
  62.     }
  63.     
  64.     printf("\n\n出栈数据\n");
  65.     while(Pop(top, &ch))         /*出栈*/
  66.         printf("%d\n",ch);
  67.     
  68.     return 0;
  69. }
阅读(1403) | 评论(0) | 转发(2) |
0

上一篇:TCS230

下一篇:队列应用编程

给主人留下些什么吧!~~