堆栈(数组实现)
来源:互联网 发布:dlna投屏软件 编辑:程序博客网 时间:2024/05/12 05:41
/* array for stack * top: 栈顶指针,指向最后一个元素的下一个空位置 */#include<stdio.h>#include<stdlib.h>#define MAX5 //size of queueint stack[MAX];int top;void push(int stack[], int *top, int value){if(*top < MAX) {stack[(*top)++] = value;} else {printf("Stack overflow\n");exit(0);}}void pop(int stack[], int *top, int *value){if(*top > 0) {*value = stack[--(*top)];} else {printf("Stack underflow\n");exit(0);} }void item(){ printf("*************** Welcome to the Stack *************\n"); printf("1: Push an element;\n"); printf("2: Pop an element;\n"); printf("0: Exit.\n"); printf("*************************************************\n"); printf("Select your operation: ");}void printStack(int stack[], int top){int i;printf("{ ");for(i=0; i<MAX; i++) { printf("%d ", stack[i]);if(i == top-1)printf("} ");}putchar('\n');}main(void){char item_choice;int n;item();while(1) { item_choice = getchar(); switch (item_choice) { case '1': printf("Push an element: "); scanf("%d", &n); push(stack, &top, n); printf("\nQueue: "); printStack(stack, top); putchar('\n'); item(); break; case '2': printf("Pop an element: "); pop(stack, &top, &n); printf("Element: %d\n", n); printf("Queue: "); printStack(stack, top); putchar('\n'); item(); break; case '0': printf("Good luck to you!\n"); return 0; } } return;}