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 struct SNode *PtrToSNode;
10 struct SNode
11 {
12     ElementType Data;
13     PtrToSNode Next;
14 };
15 typedef PtrToSNode Stack;
16 
17 Stack CreateStack();       //链栈的构建
18 bool IsEmpty(Stack S);    //判断栈是否为空
19 void Push(Stack S, ElementType X);    //入栈
20 ElementType Pop(Stack S);     //出栈
21 
22 
23 Stack CreateStack()       //链栈的构建
24 {
25     Stack S;
26 
27     S = malloc(sizeof(struct SNode));
28     S->Next = NULL;
29     return S;
30 }
31 
32 bool IsEmpty(Stack S)    //判断栈是否为空
33 {
34     return (S->Next == NULL);
35 }
36 
37 void Push(Stack S, ElementType X)    //入栈
38 {
39     PtrToSNode TmpCell;
40 
41     TmpCell = (PtrToSNode)malloc(sizeof(struct SNode));
42     TmpCell->Data = X;
43     TmpCell->Next = S->Next;
44     S->Next = TmpCell;
45 }
46 
47 ElementType Pop(Stack S)     //出栈
48 {
49     if(IsEmpty(S))
50     {
51         printf("栈为空,出栈失败!\n");
52         return false;
53     }
54 
55     PtrToSNode FirstCell;
56     ElementType TopElem;
57 
58     FirstCell = S->Next;
59     TopElem = FirstCell->Data;
60     S->Next = FirstCell->Next;
61     free(FirstCell);
62     return TopElem;
63 }

 

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