繁体   English   中英

使用C中的链表实现队列时出错

[英]Error implementing queue using linked list in C

我正在使用C中的链接列表实现队列。这是我的结构-

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

我在执行push()时遇到问题。 这是我的push()定义-

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;
}

这是我的main()函数-

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;
        }
    }
}

现在的问题是,在case 1 push()退出后, head再次变为NULL ,即此处被捕获! 语句确实得到执行。 这怎么可能?

由于您要按值调用并且要修改值(在本例中为节点* head),因此该值不会保留在main() 所以要么

  1. 将指针传递到节点* head

    push(&head,n); main()

    并修改

    void push(node **head,int n)

  2. 回头

    node* push(node *head,int n)

    并在main()

    head=push(head,n);

只需添加已接受的答案,另一种选择就是将head变量声明为global。 然后,您无需将head作为参数来推送或弹出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM