1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #define OK 1 5 #define ERR 2 6 #define TRUE 1 7 #define FALSE 0 8 #define MAXSIZE 20 //定义栈的最大长度 9 10 typedef int status; //定义函数返回的状态,OK & ERR 11 typedef char datatype; //定义栈中每个元素的数据类型,这里暂定为字符型 12 13 typedef struct { 14 datatype data[MAXSIZE]; //存储着栈中的每个元素 15 int top; //用于标识栈顶,永远保存着栈顶元素的下标 16 } SequenceStack; 17 18 /* 函数原型,栈的基本操作 */ 19 SequenceStack *createSequenceStack(void); 20 status isEmpty(SequenceStack *L); 21 void clear(SequenceStack *L); 22 datatype getTop(SequenceStack *L); 23 int getLength(SequenceStack *L); 24 status push(SequenceStack *L, datatype node_to_push); 25 datatype pop(SequenceStack *L); 26 void showStack(SequenceStack *L); 27 28 int main(){ 29 /* 测试 */ 30 SequenceStack *root; //指向一个通过createSequenceStack函数创建的栈 31 root=createSequenceStack(); 32 printf("isEmpty = %d ",isEmpty(root)); 33 printf("Length = %d ",getLength(root)); 34 push(root,'a'); 35 push(root,'b'); 36 push(root,'c'); 37 push(root,'d'); 38 printf("isEmpty = %d ",isEmpty(root)); 39 printf("Length = %d ",getLength(root)); 40 showStack(root); 41 putchar(' '); 42 printf("pop = %c ",pop(root)); 43 printf("pop = %c ",pop(root)); 44 printf("getTop = %c ",getTop(root)); 45 printf("isEmpty = %d ",isEmpty(root)); 46 printf("Length = %d ",getLength(root)); 47 showStack(root); 48 putchar(' '); 49 clear(root); 50 printf("isEmpty = %d ",isEmpty(root)); 51 printf("Length = %d ",getLength(root)); 52 53 return 0; 54 } 55 56 SequenceStack *createSequenceStack(void){ 57 SequenceStack *tmp; 58 tmp=malloc(sizeof(SequenceStack)); //void*类型指针能自动转为其他类型的指针 59 tmp->top=-1; 60 //初始化栈的栈顶指针,-1代表空栈,0表示只有一个元素的栈,那个元素就是数组下标0,依次类推 61 return tmp; 62 } 63 status isEmpty(SequenceStack *L){ 64 if (L->top==-1) 65 return TRUE; 66 else 67 return FALSE; 68 } 69 void clear(SequenceStack *L){ 70 L->top=-1; 71 } 72 datatype getTop(SequenceStack *L){ 73 return L->data[L->top]; 74 } 75 int getLength(SequenceStack *L){ 76 return L->top+1; 77 } 78 status push(SequenceStack *L, datatype node_to_push){ 79 //node_to_insert表示想要入栈的元素 80 if (L->top==MAXSIZE-1) return ERR; //满栈 81 L->top++; //栈顶指针+1 82 L->data[L->top]=node_to_push; //将新元素入栈 83 return OK; 84 } 85 datatype pop(SequenceStack *L){ 86 datatype s; 87 if (L->top==-1) return ERR; //空栈 88 s=L->data[L->top]; //将要出栈的元素先赋值给临时变量s 89 L->top--; //栈顶指针-1 90 return s; //返回出栈的元素的值 91 } 92 void showStack(SequenceStack *L){ 93 int i; 94 int total=getLength(L); 95 for (i=0; i<total; i++){ 96 printf("%c ",L->data[i]); 97 } 98 } 99 /* 100 栈的定义:仅限定在表尾进行插入和删除操作的线性表,即操作受限的线性表 101 一般,把允许插入和删除的一端作为栈顶,另一端则是栈底 102 不含任何元素的栈就是空栈 103 所以,栈又称后进先出(Last in First out)的线性表 104 */ 105 /* 环境: Code::Blocks with GCC 5.1 */
运行截图: