C语言链栈,栈顶元素返回问题

BEI_TIAN_XUAN
  • 7

求求各位大佬了,为什么a返回的是地址啊!

#include<stdio.h>
#include<stdlib.h>
typedef int Status;
typedef int ElemType;
#define TRUE 1;
#define ERROR 0;
typedef struct Node
{
    ElemType data;
    struct Node* next;
}StackNode,*StackList;
Status InitStack(StackList S);    //初始化(无头结点)
Status Push(StackList S, ElemType e);  //头插法
Status Pop(StackList S, ElemType* a);   //弹出
int main()
{
    int n;
    ElemType e, a;
    StackList S;
    S = (StackList)malloc(sizeof(StackNode));
    if (InitStack(S) == 1)
    {
        printf("恭喜!构建空链栈成功!\n");
    }
    printf("请输入插入元素个数:");
    scanf("%d", &n);
    printf("请输入插入栈的元素:");
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &e);
        Push(S, e);
    }
        printf("恭喜你!插入成功!\n");  
    if (Pop(S, &a) == 1)
    {
        printf("恭喜你!出栈成功!\n");
        printf("删除栈顶元素:%d\n", a);
    }

    return 0;
}
Status InitStack(StackList S)
{
    S = NULL;

    return TRUE;
}
Status Push(StackList S, ElemType e)
{
    StackList P;
    P = (StackList)malloc(sizeof(StackNode));
    P->data = e;
    P->next = S->next;
    S = P; //修改栈定指针

    return TRUE;
}
Status Pop(StackList S, ElemType *a)
{
    StackList P;
    P = S;
    if (P == NULL)
        return ERROR;
    *a = S->data;
    S = S->next;
    free(P);
    
    return TRUE;
}
评论
阅读 207
2 个回答

订正后的源码;

#include<stdio.h>
#include<stdlib.h>
typedef int Status;
typedef int ElemType;
#define TRUE 1;
#define ERROR 0;
typedef struct Node
{
    ElemType data;
    struct Node* next;
}StackNode,*StackList;
Status InitStack(StackList S);    //初始化(无头结点)
Status Push(StackList S, ElemType e);  //头插法
Status Pop(StackList S, ElemType* a);   //弹出
int main()
{
    int n;
    ElemType e, a;
    StackList S;
    S = (StackList)malloc(sizeof(StackNode));
    if (InitStack(S) == 1)
    {
        printf("恭喜!构建空链栈成功!\n");
    }
    printf("请输入插入元素个数:");
    scanf("%d", &n);
    printf("请输入插入栈的元素:");
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &e);
        Push(S, e);
    }
        printf("恭喜你!插入成功!\n");  
    if (Pop(S, &a) == 1)
    {
        printf("恭喜你!出栈成功!\n");
        printf("删除栈顶元素:%d\n", a);
    }

    return 0;
}
Status InitStack(StackList S)
{
    S = NULL;

    return TRUE;
}
Status Push(StackList S, ElemType e)
{
    StackList P;
    P = (StackList)malloc(sizeof(StackNode));
    P->data = e;
    P->next = S->next;
    S->next = P; //修改栈顶指针
    return TRUE;
}
Status Pop(StackList S, ElemType* a)
{
    StackList P;
    P = S->next;
    if (S == NULL)
        return ERROR;
    S->next = P->next;
    *a = P->data;
    free(P);
    return TRUE;
}

因为你的栈顶指针一直没有改变过
Push函数中的S = P; //修改栈定指针这行代码是有问题的,因为传参时候是值传递,Push内部修改S的值根本不会影响到外部的S

撰写回答

登录后参与交流、获取后续更新提醒

宣传栏