C语言—栈

栈的操作:进栈和出栈

 1 #include "stdafx.h"
 2 #include "stack.h"
 3 #define maxsize  20
 4 typedef int Elemtype;
 5 
 6 /*顺序存储—数组形式*/
 7 struct stack
 8 {
 9     int data[maxsize];
10     int top;
11 };
12 
13 void init(struct stack *ps)
14 {
15     ps->top = -1;
16 }
17 
18 void init2(struct Doublestack * ps)
19 {
20     ps->top1 = -1;
21     ps->top2 =maxsize;
22 }
23 
24 void  print(int a[],int len)
25 {
26     int i;
27     // len = sizeof(a) / sizeof(a[0]);这样子你得不到长度的,此时a退化为了指针
28     for (i = 0; i <= len - 1; i++)
29     {
30         printf("%d\n", a[i]);
31     }
32 }
33 int push(struct stack * s, int e)
34 {
35     if (s->top == maxsize - 1)
36         return -1;    
37     s->data[++s->top] = e;    
38     return 0;
39 }
40 
41 Elemtype  pop(struct stack *s)
42 {
43     int n;
44     if (s->top == 0)
45         return -1;
46     n = s->data[s->top--];
47     
48     return n;
49 }
50 
51 //两栈共享
52 struct Doublestack
53 {
54     int data[maxsize];
55     int top1;
56     int top2;
57 };
58 
59 int push_two(struct Doublestack *s, int e, int stackflag)
60 {
61     if (s->top1 == s->top2 - 1)  //full stack
62         return -1;
63     if (stackflag == 1)
64     {
65         s->data[++s->top1] = e;
66     }
67     else if (stackflag == 2)
68     {
69         s->data[--s->top2] = e;
70     }
71     return 0;
72 }
73 Elemtype pop_two(struct Doublestack *s,  int stackflag)
74 {
75     int n;
76     if (stackflag == 1)
77     {
78         if (s->top1 == -1)  //s1 empty
79             return -1;
80         n = s->data[s->top1--];
81     }
82     else if (stackflag == 2)
83     {
84         if (s->top2 ==maxsize)  //s2 empty
85             return -1;
86         n = s->data[s->top2++];
87     }
88     //printf("%d\n", n);
89     return n;
90 }

主函数

 1 #include "stdafx.h"
 2 #include  "link.h"
 3 #include "stack.h"
 4 
 5 int main()
 6 {
 7     
 8     /*stack_test*/
 9     //struct stack s;
10     //struct stack *ps = &s;
11     //init(ps);
12 
13     struct Doublestack s;
14     struct Doublestack * ps = &s;
15     init2(ps);
16     int e = 1;
17     int n;
18     //push( ps,  e);
19     //push(ps, 2);
20     //print(ps->data,2);
21     //n = pop(ps);
22     //printf("%d\n", n);
23 
24     push_two(ps, e,1);
25     push_two(ps, 2, 2);
26     print(ps->data, 20);
27      n=pop_two(ps,1);
28     printf("n =%d\n", n);
29 
30     system("pause");
31 
32 
33 }

 

posted @ 2019-03-27 10:21  刘海儿啊  阅读(211)  评论(0编辑  收藏  举报