1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
| #include<stdio.h> #include<iostream> #include<stdlib.h> #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define OVERFLOW -2 #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 typedef int Status; typedef int SElemType; using namespace std; typedef struct { SElemType *base; SElemType *top; int stacksize; }SqStack; Status InitStack(SqStack &S) { S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType)); if (!S.base) exit(OVERFLOW); S.top = S.base; S.stacksize = STACK_INIT_SIZE; return OK; } Status StackEmpty(SqStack &S) { if (S.top == S.base) { return TRUE; } else return FALSE; } Status GetTop(SqStack &S, SElemType &e) { if (S.top == S.base) return ERROR; e= *(S.top-1); return OK; } Status Push(SqStack &S, SElemType e) { if (S.top - S.base >= S.stacksize) { S.base = (SElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemType)); if (!S.base) exit(OVERFLOW); S.top = S.base + S.stacksize; S.stacksize += STACKINCREMENT; } *S.top++ = e; return OK; } Status Pop(SqStack &S, SElemType &e) { if (S.top == S.base) return ERROR; e = *--S.top; return OK; } Status Stackoutput(SqStack &S) { SElemType *p; if (S.top == S.base) return ERROR; p = S.base; while (p != S.top) { printf("%d ", *p); p++; } return OK; } Status StackTraverse(SqStack &S) { SElemType *p; if (S.top == S.base) return ERROR; p = S.top - 1; while (p != S.base - 1) { printf("%d ", *p); p--; } return OK; } void main() { int i, n, k, h, a, b; SqStack S; printf("创建一个空栈!\n"); InitStack(S); printf("判断栈是否为空!\n"); printf("StackEmpty(S)=%d\n", StackEmpty(S)); printf("创建栈的元素个数:\n"); cin >> n; printf("输入%d个入栈元素的值:\n", n); for (i = 0; i < n; i++) { cin >> k; Push(S, k); } printf("逆序输出顺序栈元素值:\n"); Stackoutput(S); printf("输出顺序栈元素值:\n"); StackTraverse(S); printf("输入入栈元素值:"); cin >> h; Push(S, h); printf("输出入栈后的顺序栈元素值:\n"); StackTraverse(S); Pop(S, a); printf("输出第一个出栈元素值:%d\n", a); Pop(S, a); printf("输出第二个出栈元素值:%d\n", a); printf("输出两次出栈后顺序栈元素值:"); StackTraverse(S); GetTop(S, b); printf("输出栈顶元素值:%d\n", b); system("pause"); }
|