欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

栈的简单实现

程序员文章站 2022-03-22 16:24:22
...

一、头文件、宏及函数声明:

#include <stdio.h>
#include <stdlib.h>
#define MAX 100

typedef enum status {
    success, overflow, underflow, fatal
} Status;

typedef int StackEntry;

typedef struct stack {
    int top;
    StackEntry* entry;
    int stack_size;
} Stack, *StackPtr;

Status Stack_push(StackPtr s, StackEntry item);
Status Stack_Pop(StackPtr s, StackEntry* item);
Status Stack_Top(StackPtr s, StackEntry* item);

 

二、函数实现:

Status Stack_push(StackPtr s, StackEntry item) {
    Status outcome = success;
    if(s->top == MAX-1) {
        outcome = overflow;
    } else {
        s->top++;
        s->entry[s->top] = item;
    }
    return outcome;
}

Status Stack_Pop(StackPtr s, StackEntry* item) {
    Status outcome = success;
    if(s->top == -1) {
        outcome = underflow;
    } else {
        *item = s->entry[s->top--];
    }
    return outcome;
}

Status Stack_Top(StackPtr s, StackEntry* item) {
    Status outcome = success;
    if(s->top == -1) {
        outcome = underflow;
    } else {
        *item = s->entry[s->top];
    }
    return outcome;
}