码迷,mamicode.com
首页 > 编程语言 > 详细

栈的数组实现

时间:2015-09-23 11:48:24      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

声明 cursor_stack.h:

 1 #ifndef CURSOR_STACK_H_INCLUDED
 2 #define CURSOR_STACK_H_INCLUDED
 3 struct StackRecord;
 4 typedef struct StackRecord *Stack;
 5 
 6 int IsEmpty(Stack S);
 7 int IsFull(Stack S);
 8 Stack CreateStack(int MaxElements);
 9 void DisposeSatck(Stack S);
10 void MakeEmpty(Stack S);
11 void Push(int X, Stack S);
12 int Top(Stack S);
13 void Pop(Stack S);
14 int TopAndPop(Stack S);
15 
16 #endif // CURSOR_STACK_H_INCLUDED

实现 implementation.c:

 1 #define MinStackSize 5
 2 
 3 struct StackRecord{
 4     int Capacity;
 5     int TopOfStack;
 6     int *Array;
 7 };
 8 
 9 Stack CreateStack( int MaxElements) {
10     Stack S;
11     if(MaxElements < MinStackSize)
12         printf("Stack Too Small!");
13     S = malloc(sizeof(struct StackRecord));
14     if(S == NULL)
15         printf("Out of space!");
16     S->Array = malloc(sizeof(int) * MaxElements);
17     if(S->Array == NULL)
18         printf("Out of space!");
19     S->Capacity = MaxElements;
20     MakeEmpty(S);
21     return S;
22 }
23 
24 void MakeEmpty(Stack S) {
25     S->TopOfStack = EmptyTOS;
26 }
27 
28 int IsEmpty(Stack S) {
29     return S->TopOfStack == EmptyTOS;
30 }
31 
32 void Push(int X, Stack S) {
33     if(IsFull(S)){
34         printf("Full Stack!\n");
35     }
36     else {
37         S->Array[++S->TopOfStack] = X;
38     }
39 }
40 
41 int Top(Stack S) {
42     if(!IsEmpty(S))
43         return S->Array[S->TopOfStack];
44 }
45 
46 void Pop(Stack S) {
47     if(IsEmpty(S))
48         printf("Empty Stack");
49     else{
50         S->TopOfStack--;
51     }
52 }
53 
54 int TopAndPop(Stack S) {
55     if(!IsEmpty(S)){
56         return S->Array[S->TopOfStack--];
57     } else {
58     return 0;
59     }
60 }
61 
62 int IsFull(Stack S) {
63     return S->TopOfStack == S->Capacity - 1;
64 }

测试 main.c:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include "cursor_stack.h"
 4 
 5 int main()
 6 {
 7     Stack S;
 8     S = CreateStack(100);
 9     int i = 0;
10     for(; i < 100; i++){
11         Push(i, S);
12     }
13     printf("%d ", Top(S));
14     Push(i, S);
15     printf("%d ", Top(S));
16     Pop(S);
17     printf("%d", Top(S));
18     return 0;
19 }

 

栈的数组实现

标签:

原文地址:http://www.cnblogs.com/zsdvvb/p/4831749.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!