kxy_c++ 发表于 2021-4-5 12:46:26

堆栈的实现,不知为何运行结果很奇怪!求大佬指导

#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 10

typedef struct stack{
        int top;
        int data;
}stack;

void init_stack(stack a){
        a.top=-1;
        a.data[]
}

int stack_empty(stack a){
        if(a.top==-1) return 1;
        else return 0;
}

void show(stack a){
        if(stack_empty) printf("An empty stack!");
        int temp = a.top;
        while(temp>=0){
                printf("%d ",a.data);
                temp--;
        }
        printf("\n");
}

void push(stack a,int new_push){
        if(MAX_SIZE-1==a.top) printf("Full stack!Stop insert data!");
        else{
                ++a.top;
                a.data=new_push;
        }
}

void pop(stack a){
        if(stack_empty) printf("An empty stack!");
        else a.top--;
}

int get_top_elem(stack a){
        return a.data;
}

int main(){
        int i;
        stack a;
        init_stack(a);
        //show(a);
        for(i = 0;i<10;i++) {
                push(a,i);
                show(a);
        }
        pop(a);
        show(a);
        return 0;
}

李京 发表于 2021-4-8 19:39:17

本帖最后由 李京 于 2021-4-8 19:43 编辑

你的函数都应该传入指针,不能直接传入,这是传值和传地址的区别

你的程序21 和 39 if 判断的条件,调用函数没有加 ()


#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 10

typedef struct stack {
    int top;
    int data;
}*stack, sta; // 这里的名字我随便取的   这里我修改了stack 变成了 指针类型的了

void init_stack(stack a) { // 传入指针
    a->top = -1;
    a->data = 0;
}

int stack_empty(stack a) {
    if (a->top == -1)
    {
      printf("t->top==%d   ", a->top);
      return 1;
    }
    else return 0;
}

void show(stack a) {
    if (stack_empty(a)) printf("An empty stack!"); // 这里我改了
    int temp = a->top;
    while (temp >= 0) {
      printf("%d ", a->data);
      temp--;
    }
    printf("\n");
}

void push(stack a, int new_push) {
    if (MAX_SIZE - 1 == a->top) printf("Full stack!Stop insert data!");
    else {
      ++a->top;
      a->data = new_push;
    }
}

void pop(stack a) {
    if (stack_empty(a)) printf("An empty stack!"); // 这里的条件我改了
    else a->top--;
}

int get_top_elem(stack a) {
    return a->data;
}

int main() {
    int i;
    sta a;
    init_stack(&a); //传入地址
    //show(a);
    for (i = 0; i < 10; i++) {
      push(&a, i);
      show(&a);
    }
    pop(&a);
    show(&a);
    return 0;
}

kxy_c++ 发表于 2021-4-17 23:42:50

李京 发表于 2021-4-8 19:39
你的函数都应该传入指针,不能直接传入,这是传值和传地址的区别

你的程序21 和 39 if 判断的条件,调 ...

感谢!!!搞了好久了都没搞懂!!
!!!谢谢您!!
看了您改动后的代码如沐春风
页: [1]
查看完整版本: 堆栈的实现,不知为何运行结果很奇怪!求大佬指导