实验三 栈的基本运算

来源:互联网 发布:公安部交管局 数据 编辑:程序博客网 时间:2024/09/21 09:25

本周三(10月17日)完成 栈的基本运算的实验

实验内容:p59实训1 将十进制数转换为2进制数。

参考教材p44页介绍和以下粘的程序代码

 1 :      /*顺序栈的基本操作*/
2 : 
3 :       #include <stdio.h>
4 :    #include<malloc.h>
5 :       #define MaxSize 100
6 :       typedef char ElemType;
7 :       typedef struct
8 :       {
9 :   char stack[MaxSize];
10 :          int top;
11 :       } stacktype;
12 :       void initstack(stacktype *S)
13 :       {
14 :   S->top=-1;
15 :       }
16 :       void push(stacktype *S,ElemType x)
17 :       {
18 :         if (S->top==MaxSize) printf("栈上溢出!/n");
19 :         else
20 :         {
21 :            S->top++;
22 :            S->stack[S->top]=x;
23 :         }
24 :       }
25 :       void pop(stacktype *S)
26 :       {
27 :         if (S->top==-1) printf("栈下溢出!/n");
28 :         else S->top--;
29 :    }
30 :    ElemType gettop(stacktype *S)

31 :       {
32 :    int temp;
33 :         if (S->top==-1) printf("栈空!/n");
34 :         else {
35 :      temp=S->top;
36 :      return S->stack[S->top] ;
37 :       }
38 :    }
39 :       int empty(stacktype *S)
40 :       {
41 :         if (S->top==-1) return(1);
42 :         else return(0);
43 :       }
44 :       void display(stacktype *S)
45 :       {
46 :         int i;
47 :         printf("栈中元素:");
48 :         for (i=S->top;i>=0;i--)
49 :      printf("%c ",S->stack[i]);
50 :         printf("/n");
51 :       }
52 :
 
53 :      void main()
54 :       {
55 :         stacktype *st;
56 :      st=(stacktype *)malloc(sizeof(stacktype));
57 :         printf("建立一空栈/n");
58 :         initstack(st);
59 :         printf("栈空:%d/n",empty(st));
60 :         printf("依次插入a,b,c,d元素/n");
61 :         push(st,'a');
62 :         push(st,'b');
63 :         push(st,'c');
64 :         push(st,'d');
65 :         display(st);
66 :         printf("退一次栈/n");
67 :         pop(st);
68 :  //     printf("栈顶元素:%c/n",gettop(st));
69 :         printf("退一次栈/n");
70 :         pop(st);
71 :         display(st);
72 :       }