在C中设置堆栈

时间:2017-04-22 22:14:50

标签: c stack push pop

我正在研究基本的堆栈方法,我必须这样做,以便我的堆栈可以接受字符。我需要使用push和pop方法从堆栈中加载和卸载字符串(即" bob"," SELUR LOBOC")然后打印出结果。这就是我到目前为止所做的:

c("aa", "e", "hhhhhhh", "aa","nn","d") 

1 个答案:

答案 0 :(得分:0)

像这样

#include <stdio.h>
#include <stdbool.h>

typedef bool boolean;

typedef char* Type;

#define PRN_TYPE "%s"

enum { CAPACITY = 5, EMPTY = -1 };

Type stack[CAPACITY];

int top = EMPTY;

void init(void){
    top = EMPTY;
}

void push(Type x){
    if(top+1 < CAPACITY){
        stack[++top] = x;
    } else {
        fprintf(stderr, "Stack full! Can't push '" PRN_TYPE "'.\n", x);
    }
}

Type pop(void){
    return stack[top--];
}

boolean isStackEmpty(void){
    return top == EMPTY;
}

int main(void){
    init();
    push("red");
    push("blue");
    push("green");
    push("yellow");
    push("brown");
    push("purple");

    while(!isStackEmpty()){
        printf(PRN_TYPE "\n", pop());
    }
}