我正在研究基本的堆栈方法,因此必须使之能够使我的堆栈接受字符。我需要使用push和pop方法,我必须从堆栈中加载和卸载字符串(即“ bob”,“ SELUR LOBOC”),然后打印出结果。这是我到目前为止所拥有的:
#include <stdio.h>
int stack[5]= {1,2,3,4,5};
int top;
void init()
{
//set stack top pointer too -1
top = -1;
}
void push(int x)
{
//increment stack pointer
top = top+1;
//place x on top of stack
stack[top] = x;
}
int pop(){
int x;
//retrieve item from top of stack.
x = stack[top];
//decrement stack
top = top-1;
return x;
}
boolean isStackEmpty(){
boolean empty;
empty = false;
//if top = -1, the stack is empty
if(top == -1){
empty = true;
}
return empty;
}
int main(void)
{
printf(pop);
}
最佳答案
像这样
#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());
}
}
关于c - 在C中设置堆栈,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43565231/