实施队列错误使用联用C列表 [英] Error implementing queue using linked list in C

查看:142
本文介绍了实施队列错误使用联用C列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实施使用链表队列中C.这是我的结构 -

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

这是我的的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;
        }
    }
}

现在的问题是,经过推()退出在案例1 变成 NULL 再次,即在这里一网打尽!的语句不会被执行。这怎么可能?

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?

推荐答案

既然你是按值调用和要修改的值(在这种情况下,节点*头),该值将不保留在主()。因此,无论

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. 传递指针节点*头

  1. Pass pointer to node *head

推(安培;头,N); 的main()

和修改

无效的push(节点**头,INT N)

返回头

节点*推(节点*头,INT N)

的main()

=头推(头,N);

这篇关于实施队列错误使用联用C列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆