链栈的基本操作之取栈顶元素的值

#include<stdio.h>
#include<malloc.h>
typedef int datatype;
typedef struct Node
{
    datatype data;
    struct Node *next;
}Node;
Node *top=(Node *)malloc(sizeof(Node));
void build(Node *top)
{
    top=NULL;
}
void push(Node *top,datatype x)
{
    Node *s=(Node *)malloc(sizeof(Node));
    s->data=x;
    s->next=top;
    top=s;
}

int gettop(Node *top,datatype *ptr)
{
    if(top==NULL)
    {
        printf("栈顶无元素\n");
        return 0;
    }
    *ptr=top->data ;
    return 1;
}
int main(){
    datatype x;
    build(top);
    printf("现将5和99进行入栈\n");
    push(top,5);
    push(top,99);
    if(gettop(top,&x)==1)
    printf("当前栈顶元素是%d\n",x); 

    return 0;
}

为什么最后取不出来栈顶元素呢,取出来的是一个很大的数,恳请大佬为在线小白指点一下

学习不易,小白叹气

Node *top=(Node *)malloc(sizeof(Node));
void build(Node *top)
{
    top=NULL;
}

 

 build(top);

你这是怎么个意思呢?有点搞不清楚啊。

==========

int main(){
    datatype x;
    Node *top=(Node *)malloc(sizeof(Node));

printf("现将5和99进行入栈\n");
    push(top,5);
    push(top,99);
    if(gettop(top,&x)==1)
    printf("当前栈顶元素是%d\n",x); 

    return 0;
}

或者:

Node *top=(Node *)malloc(sizeof(Node));
void build(Node *top)
{
    top=NULL;
}改为
void build(Node *top)
{
    top=(Node *)malloc(sizeof(Node));
}

 

int main(){
    datatype x;
    Node *top = NULL;

build(top);

printf("现将5和99进行入栈\n");
    push(top,5);
    push(top,99);
    if(gettop(top,&x)==1)
    printf("当前栈顶元素是%d\n",x); 

    return 0;
}

初始化这个链栈