Loading

顺序栈

 

 

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 #define false 0
 5 #define true 1
 6 
 7 typedef int ElementType;
 8 typedef int bool;
 9 typedef int Position;
10 typedef struct SNode *PtrToSNode;
11 struct SNode
12 {
13     ElementType *Data;
14     Position Top;
15     int MaxSize;
16 };
17 typedef PtrToSNode Stack;
18 
19 
20 Stack CreateStack(int MaxSize);       //顺序栈的构建
21 bool IsEmpty(Stack S);    //判断栈是否为空
22 bool IsFull(Stack S);     //判断栈是否已满 
23 bool Push(Stack S, ElementType X);    //入栈
24 ElementType Pop(Stack S);     //出栈
25 
26 
27 
28 Stack CreateStack(int MaxSize)       //顺序栈的构建
29 {
30     Stack S = (Stack)malloc(sizeof(struct SNode));
31     S->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
32     S->Top = -1;
33     S->MaxSize = MaxSize;
34     return S;
35 }
36 
37 bool IsEmpty(Stack S)    //判断栈是否为空
38 {
39     return (S->Top == -1);
40 }
41 
42 bool IsFull(Stack S)     //判断栈是否已满    
43 {
44     return (S->Top == S->MaxSize-1);
45 }
46 
47 bool Push(Stack S, ElementType X)    //入栈
48 {
49     if(IsFull(S))
50     {
51         printf("栈已经满了,入栈失败!\n");
52         return false;
53     }
54     else
55     {
56         ++S->Top;
57         S->Data[S->Top] = X;
58         return true;
59     }
60 }
61 
62 ElementType Pop(Stack S)     //出栈
63 {
64     if(IsEmpty(S))
65     {
66         printf("栈为空,出栈失败!\n");
67         return false;
68     }
69     else
70         return (S->Data[(S->top)--]);
71 }

 

posted @ 2018-09-30 09:10  拾月凄辰  阅读(141)  评论(0编辑  收藏  举报