Error implementing queue using linked list in C

自作多情 提交于 2019-12-11 18:05:17

问题


I'm implementing a queue using linked lists in C. Here's my structure -

typedef struct llist node;
struct llist
{
    int data;
    node *next;
};

I'm facing problem while executing push(). Here's my push() definition -

void push(node *head,int n)
{
    if (head==NULL)
    {
        head=(node *)(malloc((sizeof(node))));
        head->data=n;
        head->next=NULL;
        printf("=>%d\n",head->data);
    }
    else
    {
        node *ptr;
        ptr=head;
        while(ptr->next!=NULL)
        {
            ptr=ptr->next;
        }
        ptr->next=(node *)(malloc((sizeof(node))));
        ptr=ptr->next;
        ptr->data=n;
        ptr->next=NULL;
    }
    return;
}

and here's my main() function -

int main()
{
    int choice,n;
    node *head;
    head=NULL;
    while(1)
    {
        printf("Enter your choice -\n1. Push\n2. Pop\n3. Exit\n");
        scanf("%d",&choice);
        switch(choice)
        {
            case 1:
                printf("Enter element to push: ");
                scanf("%d",&n);
                push(head,n);
                if (head==NULL)//To check if head is NULL after returning from push()
                {
                    printf("Caught here!\n");
                }
                break;
            case 2:
                pop(head);
                break;
            case 3:
                return 0;
        }
    }
}

Now the problem is that after push() exits in case 1, head becomes NULL again, ie, the Caught here! statement does get executed. How is it possible?


回答1:


Since you are calling by value and you are modifying the value (in this case node *head), the value is not retained in main(). So either

  1. Pass pointer to node *head

    push(&head,n); in main()

    and modify

    void push(node **head,int n)

  2. Return head

    node* push(node *head,int n)

    and in main():

    head=push(head,n);




回答2:


Just adding to the accepted answer, another option would be to declare head variable as global. Then you don't need to pass head as a parameter to push or pop.



来源:https://stackoverflow.com/questions/21682633/error-implementing-queue-using-linked-list-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!