[數據結構與算法] : 棧的鏈式實現
阿新 • • 發佈:2017-09-10
creat 測試文件 stderr reat sem col for create eat
頭文件
1 typedef int ElementType; 2 3 #ifndef _STACKLI_H_ 4 #define _STACKLI_H_ 5 6 struct Node; 7 typedef Node *PtrToNode; 8 typedef PtrToNode Stack; 9 10 int IsEmpty(Stack S); 11 Stack CreateStack(void); 12 void DisposeStack(Stack S); 13 void MakeEmpty(Stack S); 14 void Push(ElementType X, Stack S);15 ElementType Top(Stack S); 16 void Pop(Stack S); 17 18 #endif
源文件
1 #include "stackli.h" 2 #include <malloc.h> 3 #include <stdlib.h> 4 5 struct Node 6 { 7 ElementType Element; 8 PtrToNode Next; 9 }; 10 11 int IsEmpty(Stack S) 12 { 13 returnS->Next == NULL; 14 } 15 16 // 創建棧的頭節點 17 Stack CreateStack(void) 18 { 19 Stack S = (Stack)malloc( sizeof(struct Node) ); 20 if( S == NULL ) 21 { 22 fprintf(stderr, "%s\n", "Out of space!!!"); 23 exit(-1); 24 } 25 S->Next = NULL; 26 return S;27 } 28 29 // 銷毀棧(包括頭節點) 30 void DisposeStack(Stack S) 31 { 32 MakeEmpty(S); 33 free(S); 34 } 35 36 // 清空棧就是彈出所有數據 37 void MakeEmpty(Stack S) 38 { 39 if(S == NULL) 40 { 41 fprintf(stderr, "%s\n", "Must use CreateStack first"); 42 exit(-1); 43 } 44 else 45 while( !IsEmpty(S) ) 46 Pop(S); 47 } 48 49 // 進棧, 插入到頭節點之後 50 void Push(ElementType X, Stack S) 51 { 52 PtrToNode TmpCell = (PtrToNode)malloc( sizeof(struct Node) ); 53 if(TmpCell == NULL) 54 { 55 fprintf(stderr, "%s\n", "Out of space!!!"); 56 exit(-1); 57 } 58 else 59 { 60 TmpCell->Element = X; 61 TmpCell->Next = S->Next; 62 S->Next = TmpCell; 63 } 64 } 65 66 // 返回棧頂元素, 註意S不能為空 67 ElementType Top(Stack S) 68 { 69 if( IsEmpty(S) ) 70 { 71 fprintf(stderr, "%s\n", "Empty stack"); 72 return -1; 73 } 74 else 75 return S->Next->Element; 76 } 77 78 // 出棧, 刪除頭節點的後繼 79 void Pop(Stack S) 80 { 81 if( IsEmpty(S) ) 82 { 83 fprintf(stderr, "%s\n", "Empty stack"); 84 } 85 else 86 { 87 PtrToNode P = S->Next; 88 S->Next = P->Next; 89 free(P); 90 } 91 }
測試文件
1 #include <stdio.h> 2 #include "stackli.h" 3 4 main( ) 5 { 6 Stack S; 7 int i; 8 9 S = CreateStack( ); 10 for( i = 0; i < 10; i++ ) 11 Push( i, S ); 12 13 while( !IsEmpty( S ) ) 14 { 15 printf( "%d ", Top( S ) ); 16 Pop( S ); 17 } 18 19 DisposeStack( S ); 20 return 0; 21 }
[數據結構與算法] : 棧的鏈式實現