p249 简单的动态栈算法的实现, 至于算法分析, 习题9给出了分析过程。 #include "stdio.h" #define STACK_TOTAL_SIZE (1<<4) // 16 size #define STACK_NUM 4 static int stack_mem[STACK_TOTAL_SIZE]; static int base[STACK_NUM + 1]; static int top[STACK_NUM]; /********************************************************** * function name: stack_init * return value: NONE * args: NONE * ********************************************************/ static void stack_init (void) { int i = 0; for (; i < STACK_NUM; ++i) { base[i] = (STACK_TOTAL_SIZE / STACK_NUM) * i; top[i] = base[i]; } base[STACK_NUM] = STACK_TOTAL_SIZE; return; } /********************************************************** * function name: stack_adjust * return value: 1 for success and 0 for failed * args: i, the stack that needs to be adjusted * ********************************************************/ static int stack_adjust (int i) { int k; int m, n; /* Find the smallest k for which i < k < STACK_NUM p247-a) */ for (k = i + 1; k < STACK_NUM; ++k) { if (top[k] < base[k + 1]){ break; } } /* Find the smallest k, move the data */ if (k < STACK_NUM) { m = top[k]; while (m > base[i + 1]) { stack_mem[m + 1] = stack_mem[m]; --m; } /*update the base and top*/ for (m = i + 1; m <= k; ++m) { base[m]++, top[m]++; } return 1; /* success */ } /* Find the lagest k */ for (k = i - 1; k >=0; --k) { if (top[k] < base[k + 1]) { break; } } /* find it */ if (k >= 0) { m = base[k + 1]; while (m <= top[i]) { stack_mem[m - 1] = stack_mem[m]; ++m; } /* update the base and the top */ for (m = k + 1; m <= i; ++m) { base[m]--, top[m]--; } return 1; } /* all room have filled fully */ return 0; } /********************************************************** * function name: push_stack * return value: 1 for success and 0 for overflow * args: value , stack * ********************************************************/ static int push_stack (int value, int s) { /* judge if need stack adjust */ if (top[s] == base[s + 1]) { if (!stack_adjust(s)) { printf("Error, The stack is FULL/n"); return 0; } } top[s]++; stack_mem[top[s]] = value; return 1; } static void print_base_top (void) { int i; printf("/n"); for (i = 0; i < STACK_NUM; ++i) { printf("[%d, %d]", base[i], top[i]); } printf("/n"); return; } int main (int argc, char** argv) { int value, stack; stack_init(); while (1) { printf("/n Input the value and satck:"); scanf("%d", &value); scanf("%d", &stack); if (stack == -1) { break; } if (stack == -2) { print_base_top(); } if(stack > STACK_NUM || stack < 0) { printf("/n Nonexist stack."); continue; } if (!push_stack(value, stack)) { printf("/nThe stack is FULL, exit."); break; } } printf("/nexit"); getchar(); return 0; }