堆栈与数组不同之处在于,数组可以按下标随机访问,这次访问a[5]下次可以访问a[1],但是堆栈的访问规则被限制为Push和Pop两种操作,Push(入栈或压栈)向栈顶添加元素,Pop(出栈或弹出)则取出当前栈顶的元素,也就是说,只能访问栈顶元素而不能访问栈中其它元素。如果所有元素的类型相同,堆栈的存储也可以用数组来实现,访问操作可以通过函数接口提供。
1
2
3 char stack[ 26 ];
4 /* = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'} */
5
6 int top = 0 ;
7
8 bool Push( char t)
9 {
10 if (top < sizeof (stack) / sizeof ( char ))
11 {
12 stack[top] = t;
13 top ++ ;
14 return true ;
15 }
16 printf( " \n%d\n " ,top);
17 return false ;
18 }
19
20 char Pop()
21 {
22 if ( top > 0 && top <= sizeof (stack) / sizeof ( char ) + 1 )
23 {
24 char tmp = stack[ -- top];
25 printf( " \n%c\n " ,tmp);
26 return tmp;
27 }
28 else
29 {
30 return NULL;
31 }
32 }
33
34 int main( int argc, _TCHAR * argv[])
35 {
36 int i = 97 ; /* 依稀记得 a 的 Ascii编码值为 97. */
37
38 while (Push(( char )i ++ ));
39 /* 上一句相当于 stack[26]='a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'} */
40
41 while (Pop());
42
43 getchar();
44
45 return 0 ;
2
3 char stack[ 26 ];
4 /* = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'} */
5
6 int top = 0 ;
7
8 bool Push( char t)
9 {
10 if (top < sizeof (stack) / sizeof ( char ))
11 {
12 stack[top] = t;
13 top ++ ;
14 return true ;
15 }
16 printf( " \n%d\n " ,top);
17 return false ;
18 }
19
20 char Pop()
21 {
22 if ( top > 0 && top <= sizeof (stack) / sizeof ( char ) + 1 )
23 {
24 char tmp = stack[ -- top];
25 printf( " \n%c\n " ,tmp);
26 return tmp;
27 }
28 else
29 {
30 return NULL;
31 }
32 }
33
34 int main( int argc, _TCHAR * argv[])
35 {
36 int i = 97 ; /* 依稀记得 a 的 Ascii编码值为 97. */
37
38 while (Push(( char )i ++ ));
39 /* 上一句相当于 stack[26]='a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'} */
40
41 while (Pop());
42
43 getchar();
44
45 return 0 ;
OK!
2009-7-5 11:59