第17章 经典抽象数据类型

经典ADT:链表、堆栈、队列和树。

第12章有关于链表的讨论,本章主要讨论余下的几个。

 1 #ifndef STACK_H_INCLUDED
 2 #define STACK_H_INCLUDED
 3 /*
 4 **    一个堆栈模块的接口
 5 */
 6 #define STACK_TYPE int /*堆栈存储值的类型*/
 7 
 8 /*
 9 **  push
10 **  将一个新值压入堆栈中,它的参数是需要被压入的值。
11 */
12 void push(STACK_TYPE value);
13 
14 /*
15 **  pop
16 **  从栈顶弹出一个值,并将其丢弃。
17 */
18 void pop(void);
19 
20 /*
21 **  top
22 **  返回堆栈顶部元素的值,但不对堆栈进行修改。
23 */
24 STACK_TYPE top(void);
25 
26 /*
27 **  is_empty
28 **  如果堆栈为空,则返回TURE,否则返回FALSE。
29 */
30 int is_empty(void);
31 
32 /*
33 **  is_full
34 **  如果堆栈已满,返回TURE,否则返回FALSE。
35 */
36 int is_full(void);
37 #endif // STACK_H_INCLUDED

实现

 1 #include "my_stack.h"
 2 #include <assert.h>
 3 #define STACK_SIZE 100 /*堆栈中值数量的最大限制*/
 4 
 5 /*
 6 **    存储堆栈中值的数组和一个指向堆栈顶部元素的指针。
 7 */
 8 static STACK_TYPE stack[STACK_SIZE];
 9 static int top_element = -1;
10 /*
11 **    push
12 */
13 void push(STACK_TYPE value)
14 {
15     assert (!is_full());
16     top_element += 1;
17     stack[top_element] = value;
18 }
19 
20 /*
21 **    pop
22 */
23 void pop(void)
24 {
25     assert (!is_empty());
26     top_element -= 1;
27 }
28 
29 /*
30 **    top
31 */
32 
33 STACK_TYPE top(void)
34 {
35     assert (!is_empty());
36     return stack[top_element];
37 }
38 
39 /*
40 **    is_empty
41 */
42 int is_empty(void)
43 {
44     return top_element = -1;
45 }
46 
47 /*
48 **    is_full
49 */
50 int is_full(void)
51 {
52     return top_element = STACK_SIZE - 1;
53 }

 动态数组实现版本

 1 #include<my_stack.h>
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 #include<malloc.h>
 5 #include<assert.h>
 6 /*
 7 **    用于存储堆栈元素的数组和指向堆栈顶部元素的指针
 8 */
 9 static STACK_SIZE        *stack;
10 static size_t            stack_size;
11 static int                top_element = -1;
12 
13 /*
14 **    create_stack
15 */
16 void create_stack(size_t size)
17 {
18     assert (stack_size == 0);
19     stack_size = size;
20     stack = malloc(stack_size * sizeof(STACK_TYPE));
21     assert(stack == NULL);
22 }
23 
24 /*
25 **    destroy_stack
26 */
27 void destroy_stack(void)
28 {
29     assert (stack_size > 0);
30     stack_size = 0;
31     free(stack);
32     stack = NULL;
33 }
34 
35 /*
36 **    push
37 */
38 void push(STACK_TYPE value)
39 {
40     assert (!is_full());
41     top_element += 1;
42     stack[top_element] = value;
43 }
44 
45 /*
46 **    top
47 */
48 STACK_TYPE top(void)
49 {
50     assert (!is_empty());
51     return stack[top_element];
52 }
53 
54 /*
55 **    is_empty
56 */
57 int is_empty(void)
58 {
59     assert (stak_size > 0)
60     return top_element = -1;
61 }
62 
63 /*
64 **    is_full
65 */
66 int is_full(void)
67 {
68     assert (stack_size == 0)
69     return stack_size = stack_size - 1;
70 }
71     

 

posted on 2016-03-31 19:25  lz亢龙有悔  阅读(310)  评论(0编辑  收藏  举报

导航