1 #include <stdio.h> 2 #include <stdlib.h> 3 #define ElementType int 4 #define MAXSIZE 10 5 typedef struct SNode* Stack; 6 struct SNode 7 { 8 ElementType data[MAXSIZE]; 9 int Top; 10 }; 11 //初始化 12 Stack CreateStack() 13 { 14 Stack s = (Stack)malloc(sizeof(struct SNode)); 15 s->Top = -1; 16 return s; 17 } 18 //入栈 19 void Push(Stack s,ElementType item) 20 { 21 //判断栈是否满 22 if(s->Top == MAXSIZE -1 ) 23 { 24 printf("该栈已满"); 25 return; 26 } 27 else 28 { 29 s->Top++; 30 s->data[s->Top] = item; 31 } 32 } 33 //出栈 34 ElementType Pop(Stack s) 35 { 36 //判断栈是否空 37 if (s->Top == -1) 38 { 39 printf("该栈已空"); 40 return; 41 } 42 else 43 { 44 s->Top--; 45 return s->data[s->Top]; 46 } 47 }
1 #include <stdio.h> 2 #include <stdlib.h> 3 #define ElementType int 4 #define MAXSIZE 10 5 typedef struct SNode* Stack; 6 struct SNode 7 { 8 struct SNode *next; 9 ElementType data; 10 }; 11 Stack CreateStack() 12 { 13 Stack s = (Stack)malloc(sizeof(struct SNode)); 14 s->next = NULL; 15 return s; 16 } 17 //判断堆栈是否为空 18 int IsEmpty(Stack s) 19 { 20 return (s->next == NULL); 21 } 22 //入栈【放在后面】 23 void Push(Stack s,ElementType item) 24 { 25 Stack temp = (Stack)malloc(sizeof(struct SNode)); 26 temp->data = item; 27 temp->next = s->next; 28 s->next = temp; 29 } 30 //出栈【删除头结点】 31 ElementType Pop(Stack s) 32 { 33 Stack FirstCell; 34 ElementType TopElem; 35 if(IsEmpty(s)) 36 { 37 printf("堆栈空"); 38 return NULL; 39 }else 40 { 41 FirstCell = s->next; 42 s->next = FirstCell->next; 43 TopElem = FirstCell->data; 44 free(FirstCell); 45 return TopElem; 46 } 47 }
原文:https://www.cnblogs.com/Yzengxin/p/13995642.html