实现使用链表队列我实现使用链表队列中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
,即抓到这里来!语句确实得到执行。这怎么可能?
您正在'push()'中修改列表的本地副本。要修改'main()'中的一个,你需要一个双指针。 'push()'应该是'void push(node ** head,int n)',并且在'push()'中使用'head'的任何位置,您应该使用'* head',而您应该通过'push &head,n)'当你打电话时。 – leif
'main'函数中的'head'和''pop'函数中的'head'是两个不同的变量。 – ajay