c/c++语言开发共享使用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("=>%dn",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. Pushn2. Popn3. Exitn"); 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() 。 所以要么

    只要添加到已接受的答案,另一种选择是将head变量声明为全局变量。 然后你不需要将head作为参数传递给push或pop。

      以上就是c/c++开发分享使用C中的链接列表实现队列时出错相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/519796.html

      (0)
      上一篇 2020年12月5日
      下一篇 2020年12月5日

      精彩推荐