在C中使用链表实现队列时出错
我正在用C语言中的链表实现一个队列-在C中使用链表实现队列时出错,c,linked-list,C,Linked List,我正在用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=
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;
}
}
}
现在的问题是,在
push()
退出case 1
后,head
再次变为NULL
,也就是说,在这里捕获的是!语句不会被执行。怎么可能呢?由于您是按值调用的,并且正在修改值(在本例中为node*head),因此该值不会保留在main()
中。所以
push(&head,n)代码>在main()中
修改
无效推送(节点**头部,内部n)
node*push(node*head,int n)
在main()
中:
head=push(head,n)代码>
由于您是按值调用的,并且正在修改值(在本例中为node*head),因此该值不会保留在
main()
中。所以
push(&head,n)代码>在main()中
修改
无效推送(节点**头部,内部n)
node*push(node*head,int n)
在main()
中:
head=push(head,n)代码>
除了公认的答案之外,另一个选项是将head变量声明为全局变量。然后您不需要将head作为参数传递给push或pop。只需添加到接受的答案中,另一个选项是将head变量声明为全局变量。然后不需要将head作为参数传递给push或pop。您正在
push()
中修改列表的本地副本。要修改main()
中的一个,您需要一个双指针push()
应该是void push(节点**head,int n)
并且无论在push()
中使用head
时,都应该使用*head
,并且应该通过push(&head,n)
当您调用它时。main
函数中的head
和pop
函数中的head
是两个不同的变量。您正在push()
中修改列表的本地副本。要修改main()
中的一个,您需要一个双指针push()
应该是void push(节点**head,int n)
并且无论在push()
中使用head
时,都应该使用*head
,并且应该通过push(&head,n)
当您调用它时。main
函数中的head
和pop
函数中的head
是两个不同的变量。是的,我将它作为备份选项保留了下来。但是我想知道为什么上面的代码不起作用。有什么好建议吗?是的,我把它作为备用选项。但是我想知道为什么上面的代码不起作用。有什么好建议吗。