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

004、栈的基本操作

时间:2020-05-23 21:56:01      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:进制   sizeof   创建   code   define   fine   bsp   col   pow   

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include "math.h"
  4 
  5 typedef struct demo
  6 {
  7     int* base;
  8     int* top;
  9     int stacksize;
 10 }sqstack;
 11 
 12 /* 创建一个栈 */
 13 int stackInit(sqstack* S,int n)
 14 {
 15     S->base = (int*)malloc(sizeof(int)*n);
 16     if(!S->base)
 17     {
 18         printf("stack is null!");
 19         return 0;
 20     }
 21     S->top = S->base;
 22     S->stacksize = n;
 23     return 1;
 24 }
 25 
 26 /* 清空一个栈 */
 27 void clearStack(sqstack* S)
 28 {
 29     S->top = S->base;
 30 }
 31 
 32 /* 销毁一个栈 */
 33 void destroyStack(sqstack* S)
 34 {
 35     free(S->base);
 36     S->base = S->top = NULL;
 37     S->stacksize = 0;
 38 }
 39 
 40 /* 入栈 */
 41 #define STACKINSERSIZE 10
 42 int Push(sqstack* S,int data)
 43 {
 44     if(S->top - S->base >= S->stacksize)
 45     {
 46         S->base = (int*)realloc(S->base,(S->stacksize+STACKINSERSIZE)*sizeof(int));
 47         if(!S->base)    return 0;
 48         S->top = S->base + S->stacksize;
 49         S->stacksize = S->stacksize + STACKINSERSIZE;
 50     }
 51     *(S->top) = data;
 52     S->top++;
 53 
 54     return 1;
 55 }
 56 
 57 /* 出栈 */
 58 int Pop(sqstack* S,int* data)
 59 {
 60     if(S->top == S->base)    return 0;
 61     S->top--;
 62     *data = *(S->top);
 63 }
 64 
 65 int stackLen(sqstack S)
 66 {
 67     return (S.top-S.base);
 68 }
 69 int main()
 70 {
 71     sqstack stack1;
 72     int i,len,sum = 0;
 73     int c;
 74     stackInit(&stack1,20);
 75     clearStack(&stack1);
 76     
 77     printf("please inpot 0 or 1\n");
 78 //    scanf("%c",&c);
 79     /* 输入0 or 1字符表示二进制,以 # 结束,例如:1111# */
 80     while((c = getchar()) != #)
 81     {
 82         /* 入栈 */
 83         Push(&stack1,c);
 84 //        scanf("%c",&c);
 85     }
 86     getchar();
 87     len = stackLen(stack1);
 88     printf("\nlen = %d\n",len);
 89     for(i = 0;i < len;i++)
 90     {
 91         /* 出栈 */
 92         Pop(&stack1,&c);
 93         /* 计算将二进制转换成10进制 */
 94         sum = sum + ((c - 0) * (pow(2,i)));
 95     }
 96     printf("decimal is %d\n",sum);
 97     destroyStack(&stack1);
 98     getchar();
 99     return 0;
100 }

 

004、栈的基本操作

标签:进制   sizeof   创建   code   define   fine   bsp   col   pow   

原文地址:https://www.cnblogs.com/yang-cheng/p/12944597.html

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