我正在使用C中的链表实现队列.这是我的结构 -
typedef struct llist node;
struct llist
{
int data;
node *next;
};
Run Code Online (Sandbox Code Playgroud)
我在执行时遇到问题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;
}
Run Code Online (Sandbox Code Playgroud)
这是我的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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是,push()退出后case 1,再次head成为NULL,即抓到了这里!声明确实被执行了.这怎么可能?
由于您按值调用并且正在修改该值(在本例中为node*head),因此不会保留该值main().所以要么
将指针传递给node*head
push(&head,n); 在 main()
并修改
void push(node **head,int n)
回头
node* push(node *head,int n)
并在main():
head=push(head,n);