码迷,mamicode.com
首页 > 其他好文 > 详细

C代码实现栈

时间:2015-10-17 23:37:52      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

  1 # include <stdio.h>
  2 # include <malloc.h>
  3 # include <stdlib.h>
  4 //C语言实现栈 
  5 
  6 //结点
  7 typedef struct Node{
  8     int data;//数据
  9     struct Node* pNext;//指针 
 10 }* PNODE,NODE; 
 11 
 12 //
 13 typedef struct stack{
 14     PNODE pTop;
 15     PNODE pBottom;
 16 }* PSTACK,STACK;
 17 
 18 void init(PSTACK s);
 19 void push(PSTACK s,int num);
 20 bool isEmpty(PSTACK s) ;
 21 bool pop(PSTACK s) ;
 22 void traverse(PSTACK s);
 23 void clear(PSTACK s) ;
 24 
 25 int main(void)
 26 {
 27     STACK s;
 28     init(&s);
 29     if(isEmpty(&s)){
 30         printf("栈为空\n");
 31     } 
 32     //压栈 
 33     push(&s,1);
 34     push(&s,4);
 35     push(&s,5);
 36     push(&s,77);
 37     push(&s,16);
 38     push(&s,11);
 39     push(&s,2);
 40     //遍历 
 41     traverse(&s);
 42     //出栈 
 43     if(pop(&s)){
 44         printf("出栈成功\n");
 45     }
 46     else{
 47         printf("出栈失败\n");
 48     }
 49     traverse(&s);
 50     clear(&s);
 51         if(isEmpty(&s)){
 52         printf("栈为空\n");
 53     } 
 54     return 0;
 55 }
 56 
 57 //初始化一个空栈
 58 void init(PSTACK s)
 59 {
 60     s->pTop = (PNODE)malloc(sizeof(NODE));
 61     //判断是否申请失败 
 62     if(NULL == s->pTop) {
 63         printf("内存申请失败");
 64         exit(-1);
 65     }
 66     s->pBottom = s->pTop;
 67     s->pBottom->pNext = NULL;
 68 }
 69 
 70 //压栈 
 71 void push(PSTACK s,int num)
 72 {
 73     //申请一个临时结点 
 74     PNODE tem = (PNODE)malloc(sizeof(NODE));
 75     tem->data = num;
 76     tem->pNext = s->pTop;
 77     s->pTop = tem; 
 78 }
 79 
 80 //判断栈是否为空
 81 bool isEmpty(PSTACK s) 
 82 {
 83     return s->pTop==s->pBottom;    
 84 }
 85 
 86 //出栈 
 87 bool pop(PSTACK s) 
 88 {
 89     if(isEmpty(s)){
 90         return false;
 91     }
 92     else{
 93         PNODE tem = s->pTop;
 94         s->pTop = tem->pNext;
 95         free(tem);
 96         tem = NULL;
 97         return true;
 98     }
 99 }
100 
101 //遍历栈
102 void traverse(PSTACK s)
103 {
104     PNODE p = s->pTop;
105     while(p!=s->pBottom){
106         printf("%d ",p->data);
107         p = p->pNext;
108     }
109     printf("\n");
110 }
111 
112 //清空栈
113 void clear(PSTACK s) 
114 {
115     if(isEmpty(s)){
116         return;
117     }
118     
119     PNODE p = s->pTop;
120     PNODE q = NULL;
121     while (p != s->pBottom){
122         q = p->pNext;
123         free(p);
124         p = q;
125     }
126     s->pTop = s->pBottom;
127 }

 

C代码实现栈

标签:

原文地址:http://www.cnblogs.com/makaruila/p/4888564.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!