如何使用 C 将元素压入堆栈 [英] How to push elements in a stack using C

查看:48
本文介绍了如何使用 C 将元素压入堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用 C 语言学习堆栈.但无法执行推送操作,因为它显示了一些错误.控制台中没有显示错误消息.但是在运行代码时,执行peek方法时显示了错误的top值.

I tried to learn a stack in C. But unable to do the push operation as it shows some errors in it. There is no error message shown in the console. But when running the code, it shows a wrong top value when executing the peek method.

#include<stdio.h>
#include<stdlib.h>
#define MAX 50
typedef enum{FALSE,TRUE} boolean;
typedef struct stack{
    int top;
    int a[MAX];
 }stack;
void CreateStack(stack s){
    s.top = -1;
 }
 boolean isEmpty(stack s){
    return (s.top == -1);
}
boolean isFull(stack s){
    return(s.top == MAX - 1);
}
void push(stack s, int data){
    if(isFull(s)){
        printf("Stack is Full\n");
        exit(1);
    }
    else{
        s.top = s.top + 1;
        s.a[s.top] = data;
    }
 }
 void pop(stack s){
    if(isEmpty(s)){
        printf("Stack is Empty");
        exit(1);
    }
    else{
        printf("%d\n",s.a[s.top]);
        s.top = s.top - 1;
    }
 }
 int peek(stack s){
    return s.a[s.top];
 }
 void main(){
    stack s;
    CreateStack(s);
    int num;
    push(s,1);
    push(s,2);
    push(s,15);
    printf("Top value = %d\n",peek(s));
 }

推荐答案

问题在于您没有修改作为参数传递的结构.每个函数都有一个本地副本,该副本在函数结束时不再存在.下面是 pushmain 函数的示例.对所有功能进行相同的更改.

The problem is that you are not modifying the struct you are passing as argument. Each function has a local copy which ceases to exist at the end of the function. Here is a sample of the push and main function. Make the same changes to all functions.

void push(stack *s, int data){
    if(isFull(s)){
        printf("Stack is Full\n");
        exit(1);
    }
    else{
        s->top = s->top + 1;
        s->a[s->top] = data;
    }
 }

void main(){
    stack s;
    CreateStack(&s);
    push(&s,1);
    push(&s,2);
    push(&s,15);
    printf("Top value = %d\n",peek(&s));
}

您可以避免使用 isEmptyisFullpeek 的指针,因为它们不会修改任何内容.但我认为最简单的方法是让所有这些界面都使用相同的界面.为了安全起见,您可以像 bool isFull(stack const *s)

You could avoid pointers for isEmpty, isFull and peek since they are not modifying anything. But I thought it was easiest to have the same interface for all of them. For safety, you can declare them like bool isFull(stack const *s)

这篇关于如何使用 C 将元素压入堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆