使用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()
中push()
退出之后, 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);
只要添加到已接受的答案,另一种选择是将head变量声明为全局变量。 然后你不需要将head作为参数传递给push或pop。