stack.h
1 #ifndef STACK_H_INCLUDED 2 #define STACK_H_INCLUDED 3 #include <stdbool.h> 4 5 typedef struct stack STACK; 6 7 STACK* createStack (void); 8 bool pushStack (STACK* stack, void* dataInPtr); 9 void* popStack (STACK* stack); 10 bool emptyStack(STACK* stack); 11 bool fullStack(STACK* stack); 12 STACK* destroyStack (STACK* stack); 13 void* stackTop(STACK* stack); 14 #endif // STACK_H_INCLUDED
stack.c
1 #include "stack.h" 2 #include <stdlib.h> 3 4 typedef struct node 5 { 6 void* dataPtr; 7 struct node* link; 8 } STACK_NODE; 9 10 struct stack 11 { 12 int count; 13 STACK_NODE* top; 14 }; 15 16 STACK* createStack(void) 17 { 18 STACK* stack; 19 20 stack = (STACK*) malloc(sizeof(STACK)); 21 if (stack) 22 { 23 stack->count = 0; 24 stack->top = NULL; 25 } 26 return stack; 27 } 28 29 30 bool pushStack(STACK* stack, void* dataInPtr) 31 { 32 STACK_NODE* newPtr; 33 34 newPtr = (STACK_NODE* ) malloc(sizeof(STACK_NODE)); 35 if(!newPtr) 36 return false; 37 newPtr->dataPtr = dataInPtr; 38 39 newPtr->link = stack->top; 40 stack->top = newPtr; 41 42 (stack->count)++; 43 return true; 44 } 45 46 void* popStack (STACK* stack) 47 { 48 void* dataOutPtr; 49 STACK_NODE* temp; 50 51 if (stack->count == 0) 52 dataOutPtr = NULL; 53 else { 54 temp = stack->top; 55 dataOutPtr = stack->top->dataPtr; 56 stack->top = stack->top->link; 57 free(temp); 58 (stack->count)--; 59 } 60 return dataOutPtr; 61 } 62 63 bool emptyStack(STACK* stack) 64 { 65 return (stack->count == 0); 66 } 67 68 bool fullStack(STACK* stack) 69 { 70 STACK_NODE* temp; 71 if((temp = (STACK_NODE*)malloc(sizeof(*(stack->top))))) 72 { 73 free (temp); 74 return false; 75 } 76 return true; 77 } 78 79 STACK* destroyStack (STACK* stack) 80 { 81 STACK_NODE* temp; 82 if(stack) { 83 while(stack->top != NULL){ 84 free (stack->top->dataPtr); 85 86 temp = stack->top; 87 stack->top = stack->top->link; 88 free(temp); 89 } 90 free(stack); 91 } 92 return NULL; 93 } 94 95 void* stackTop(STACK* stack) 96 { 97 if(stack->count == 0) 98 return NULL; 99 else 100 return stack->top->dataPtr; 101 }
原文:https://www.cnblogs.com/zhangleshan/p/12377101.html