简易栈的实现

20 篇文章 0 订阅

大年初一,觉得应该做一些有意义的事情。于是写了一小段程序,实现栈的部分功能。一切从简,重在理解。变量和函数的命名参考《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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值