动态数组的特点是程序在运行的时候才知道数组的长度。
9 void push(int datad);
10 void create_stack(int size);
11 void pop(void);
12 int top(void);
13 int empty();
14 int full();
15 void print();
16 void destroy_stack();
观察上面几个函数的名字就知道跟我之前写的静态数组实现堆栈其实实现起来差别不大,这里我记录一下这俩者之间的差别,
动态数组堆栈是要先动态分配好数组形式的堆栈,可以指定保存多少个元素;
删除动态数组要释放堆栈所占用的内存;
下面是动态数组实现堆栈的代码
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <assert.h>
4
5 static int stack_size;
6 static int top_element = -1;
7 static int * stack;
8
9 void push(int datad);
10 void create_stack(int size);
11 void pop(void);
12 int top(void);
13 int empty();
14 int full();
15 void print();
16 void destroy_stack();
17
18 void create_stack(int size)
19 {
20 assert(stack_size == 0);
21 stack_size = size;
22 stack = (int *)malloc(stack_size * sizeof(int));
23 if(stack == NULL)
24 printf("分配地址失败\n");
25 }
26
27 void destroy_stack()
28 {
29 assert(stack_size>0);
30 stack_size = 0;
31 stack = NULL;
32 free(stack);
33 }
34
35 void push(int data)
36 {
37 assert(!full());
38 top_element +=1;
39 stack[top_element] = data;
40 }
41
42 void pop()
43 {
44 assert(!empty());
45 top_element -=1;
46 }
47
48 int empty()
49 {
50 assert(stack_size > 0);
51 return top_element == -1;
52 }
53
54 int full()
55 {
56 assert(stack_size > 0);
57 return top_element==stack_size-1;
58 }
59
60 int top()
61 {
62 assert(!empty());
63 return stack[top_element];
64 }
65
66 void print()
67 {
68 assert(!empty());
69 int i = top_element;
70 while(i !=-1)
71 printf("%d",stack[i--]);
72 printf("\n");
73 }
74
75
76 int main()
77 {
78 create_stack(20);
79 push(9);
80 push(8);
81 push(7);
82 push(6);
83 push(5);
84 printf("压入元素后打动态数组堆栈:\n");
85 print();
86 pop();
87 pop();
88 printf("pop俩个元素之后打堆栈:\n");
89 print();
90 printf("top出来打元素:%d",top());
91 destroy_stack();
92 return 0;
93 }