top的值在主要功能中没有变化

时间:2019-11-13 21:59:24

标签: c debugging queue

我正在编写代码以使用链接列表实现Stack。以下是代码:

#include<stdio.h>
#include<stdlib.h>


struct node
{
    int data;
    struct node *next;
};
struct node *getNode();
struct node *push(struct node *);
struct node *pop(struct node *);
void display(struct node *);
int main()
{
    struct node *top, *temp;
    int n=1,ch;
    top=NULL;
    //top=getNode();
    //printf("%d",top->data);
    while(n==1)
    {
        printf("\n\nWhat do you want to do?\n1. Push\n2. Pop\n3. Display\n4. End Program\n\tYour choice=\t");
        scanf("%d",&ch);
        switch(ch)
        {
            case 1: top=push(top);
                    break;
            case 2: temp=pop(top);
                    if(temp!=NULL)
                    {
                        printf("\nPopped element is: %d",temp->data);
                        printf("\n%d",top->data);
                    }
                    break;
            case 3: display(top);
                    break;
            case 4: printf("\nExiting program!");
                    n=0;
                    break;
            default: printf("\nInvalid Input");
        }
    }
    return 0;
}
struct node *getNode()
{
        struct node *t;
        t=(struct node *)malloc(sizeof(struct node));
        printf("Enter data: ");
        scanf("%d",&(t->data));
        t->next=NULL;
        return t;
}
struct node *push(struct node *top)
{
        if(top==NULL)
        {
            struct node *t;
            t=getNode();
            top=t;
        }
        else
        {
            struct node *t;
            t=getNode();
            t->next=top;
            top=t;
        }
        return top;
}
struct node *pop(struct node *top)
{
    struct node *temp;
    temp=NULL;
    if(top==NULL)
    {
        printf("\nStack is empty");
    }
    else
    {
        temp=top;
        top=top->next;
        printf("%d",top->data);
    }
    return temp;
}
void display(struct node *top)
{
    if(top==NULL)
    {
        printf("\nStack is empty");
    }
    else
    {
        struct node *temp;
        temp=top;
        while(temp!=NULL)
        {
            printf("\n%d",temp->data);
            temp=temp->next;
        }
        printf("\n");
    }
}

其他所有工作正常,但在pop函数中,top的值更改为top-> next。但是,在主函数中它没有改变。我不知道为什么会这样。

请帮助我。谢谢!

0 个答案:

没有答案