大年初一,觉得应该做一些有意义的事情。于是写了一小段程序,实现栈的部分功能。一切从简,重在理解。变量和函数的命名参考《C语言程序设计——现代方法》。
/**************************************************
* SimpleStack.c *
* A simple stack using pointer. *
* by Eric Brown *
**************************************************/
#include<stdio.h>
#include<stdbool.h> /* C99 only */
#include<stdlib.h>
#define STACK_SIZE 10
int contents[STACK_SIZE];
int *top = 0;
void make_empty(void);
bool is_empty(void);
bool is_full(void);
void push(int i);
int pop(void);
int main(void) {
int op, num;
for(;;) {
printf("1. Initialize the stack or make the stack empty.\n");
printf("2. Judge that if the stack is empty.\n");
printf("3. Judge that if the stack is full.\n");
printf("4. Push an integer into the stack.\n");
printf("5. Pop an integer out of the stack.\n");
printf("6. Quit.\n");
printf("Please select an operation: ");
scanf("%d", &op);
switch(op) {
case 1 : make_empty(); break;
case 2 : is_empty(); break;
case 3 : is_full(); break;
case 4 :
printf("Please input the integer to push: ");
scanf("%d", &num);
push(num);
break;
case 5 : pop(); break;
case 6 : exit(EXIT_SUCCESS); break;
default : printf("Please input the number 1 to 6!\n\n");
}
}
return 0;
}
void make_empty(void) {
top = contents;
printf("The stack has been initialized!\n\n");
}
bool is_empty(void) {
bool empty = (top == contents || top == 0);
if(empty)
printf("The stack is empty!\n\n");
else
printf("The stack isn't empty!\n\n");
return empty;
}
bool is_full(void) {
bool full = (top == contents + STACK_SIZE);
if(full)
printf("The stack is full!\n\n");
else
printf("The stack isn't full!\n\n");
return full;
}
void push(int i) {
if(!top)
printf("The stack hasn't been initialized!\n\n");
else if(top == (contents + STACK_SIZE))
printf("The stack is full!\n\n");
else {
top++;
*top = i;
printf("%d has been pushed into the stack!\n\n", i);
}
}
int pop(void) {
int i;
if(top == contents || top == 0){
printf("The stack is empty or hasn't been intialized!\n\n");
return 0;
}else {
i = *top--;
printf("The top num -- %d has been popped!\n\n", i);
return i;
}
}