栈的链表实现

声明 stack.h:

 1 #ifndef STACK_H_INCLUDED
 2 #define STACK_H_INCLUDED
 3 struct Node;
 4 typedef struct Node *PtrToNode;
 5 typedef PtrToNode Stack;
 6 
 7 int IsEmpty(Stack S);
 8 Stack CreateStack(void);
 9 void DisposeStack(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 
15 #endif // STACK_H_INCLUDED

实现 implementation.c:

 1 #include<stdio.h>
 2 #include "stack.h"
 3 struct Node{
 4     int Num;
 5     PtrToNode Next;
 6 };
 7 
 8 int IsEmpty(Stack S) {
 9     return S->Next == NULL;
10 }
11 
12 Stack CreateStack(void) {
13     Stack S;
14     S = malloc(sizeof(struct Node));
15     if(S == NULL){
16         printf("Error!");
17     }
18     S->Next = NULL;
19     MakeEmpty(S);
20     return S;
21 }
22 
23 void MakeEmpty(Stack S) {
24     if(S == NULL)
25         printf("Must use CreateStack() frist");
26     while(!IsEmpty(S)){
27         Pop(S);
28     }
29 }
30 
31 void Push(int X, Stack S) {
32     PtrToNode TmpCell;
33     TmpCell = malloc(sizeof(struct Node));
34     if(TmpCell == NULL)
35         printf("Out of space!");
36     else{
37         TmpCell->Next = S->Next;
38         TmpCell->Num = X;
39         S->Next = TmpCell;
40     }
41 }
42 
43 void Pop(Stack S) {
44     PtrToNode FirstCell;
45     if(IsEmpty(S))
46         printf("Empty Stack!");
47     else{
48         FirstCell = S->Next;
49         S->Next = S->Next->Next;
50         free(FirstCell);
51     }
52 }
53 
54 int Top(Stack S) {
55     if(!IsEmpty(S)){
56         return S->Next->Num;
57     } else {
58         printf("Empty Stack");
59     }
60 }

测试 main.c:

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

 

posted on 2015-09-23 11:27  川川的小铁柱  阅读(135)  评论(0)    收藏  举报

导航