问题
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
Pass pointer to node *head
push(&head,n);inmain()and modify
void push(node **head,int n)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