在C中设置堆栈
我正在研究基本的堆栈方法,我必须使其能够接受字符。我需要使用push和pop方法从堆栈中加载和卸载字符串(即“bob”、“SELUR-LOBOC”),然后打印结果。这就是我到目前为止所做的:在C中设置堆栈,c,stack,C,Stack,我正在研究基本的堆栈方法,我必须使其能够接受字符。我需要使用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 st
#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);
}
#包括
int stack[5]={1,2,3,4,5};
int top;
void init()
{
//将堆栈顶部指针也设置为-1
top=-1;
}
无效推送(整数x)
{
//增量堆栈指针
顶部=顶部+1;
//将x放置在堆栈顶部
堆栈[顶部]=x;
}
int-pop(){
int x;
//从堆栈顶部检索项。
x=堆栈[顶部];
//减量堆栈
top=top-1;
返回x;
}
布尔值为空(){
布尔空;
空=假;
//如果top=-1,则堆栈为空
如果(顶部==-1){
空=真;
}
返回空;
}
内部主(空)
{
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());
}
}
#包括
#包括
布尔型;
typedef char*类型;
#定义PRN_类型“%s”
枚举{容量=5,空=-1};
类型堆栈[容量];
int top=空;
void init(void){
顶部=空;
}
无效推力(x型){
如果(顶部+1<容量){
堆栈[++顶部]=x;
}否则{
fprintf(stderr,“堆栈已满!无法推送”“PRN_TYPE”“。\n”,x);
}
}
类型pop(无效){
返回堆栈[top--];
}
布尔值为空(void){
返回top==空;
}
内部主(空){
init();
推(“红色”);
推(“蓝色”);
推动(“绿色”);
推(“黄色”);
推(“棕色”);
推(“紫色”);
而(!isStackEmpty()){
printf(PRN_类型“\n”,pop());
}
}
问题出在哪里?例如,没有缩进。push()上没有堆栈溢出检查。int stack[5]为什么?为什么选择5?停止bean计数,开始时只输入4096。由于printf(pop)
将指向pop
的函数指针作为第一个参数传递给printf()
,但是printf()
需要一个char*
,因此立即出现了重大问题。您不会显示任何代码读取字符、将它们推到堆栈上或弹出它们。您将无法将“COBOL规则”放入5个字符的堆栈中-您需要分配更多的空间,并且不需要对其进行预初始化,因为您将覆盖预初始化的值。我需要使用某些字符串来执行此操作。字符串的字符进入堆栈。例如:“SELUR LOBOC”字符需要被推到堆栈上,然后弹出,并打印为“COBOL RULES”@Mrs.Jones Yes。例如,使用char
作为Type
。确定。非常感谢。如何使用objects重写代码?@Mrs.Jones For non-primitive typeprintf
不能这样使用,因此您需要实现输出函数。我现在需要将此代码重写为使用队列。我该怎么做?