📣 黑五价提前开抢|VIP一年通行证5折,蓝莓、Offer多多同步特惠
查看: 1723| 回复: 2
跳转到指定楼层
上一主题 下一主题
收起左侧

[学C/C++] 求问一个关于用函数产生linked list的问题

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
写一个产生非常简单的singly linked list。写了一个push(),就是在list开头push一个item,另外一个generate_v0(), 它通过调用push()建立一个list。在main中调用generate_list(),可以得到一个给定长度的list。为什么只能得到最后push的那个数。而且为什么在main里用push()就可以建立list,用generate_v0()就不能返回正确的list?
  1. void push(linkp* headRef, int item)
  2. {        linkp new_node = new node(item);
  3.         if((*headRef)->next == NULL)
  4.                 *headRef = new_node;
  5.         else {
  6.                 new_node->next = *headRef;
  7.                 *headRef = new_node;
  8.         }
  9. }

  10. linkp generate_v0(linkp* headRef, int n)
  11. {
  12.         for(int i=1; i<=n; i++)
  13.                 push(headRef, rand()%1000);

  14.         return *headRef;
  15. }

  16. void print_item(linkp head)
  17. {       
  18.         for (;head->next != NULL; head=head->next)
  19.                 cout << head->item << endl;
  20.         cout << head->item << endl;
  21. }

  22. int main()
  23. {       
  24.         //3. demo of using push() to build a list
  25.         node* head4 = new node(0);
  26.         generate(head4, 5);
  27.         cout << "before push: " << endl;
  28.         print_item(head4);
  29.         push(&head4, 7);
  30.         push(&head4, 6);
  31.         push(&head4, 5);
  32.         push(&head4, 4);
  33.         push(&head4, 3);
  34.         push(&head4, 2);
  35.         cout << "push 7 at the begining of list with 5 element: " << endl;
  36.         print_item(head4);

  37.         //4. demo of generate_v0(), which use push to build a linked list
  38.         node *head5 = new node(0);
  39.         head5 = generate_v0(&head5, 5);
  40.         cout << "generate_v0(): " << endl;
  41.         print_item(head5);
  42. }
复制代码

点评

一楼说的对么  发表于 2013-10-4 21:29

上一篇:自己整理的常用排序算法代码_c++
下一篇:微软面试,查找第一次出现的最长重复子串
🔗
xusi 2013-10-2 01:46:09 | 只看该作者
全局:

  1. void push(linkp* headRef, int item)
  2. {
  3.     linkp new_node = new node(item);
  4.     if((*headRef)->next == NULL)
  5.         *headRef = new_node;
  6.     else {
  7.         new_node->next = *headRef;
  8.         *headRef = new_node;
  9.     }
  10. }

  11. when (*headRef) has no next node it will point to the new_node, which also does not have next node. So it will always point to a single node
复制代码

评分

参与人数 1大米 +20 收起 理由
yanyanlr + 20

查看全部评分

回复

使用道具 举报

🔗
 楼主| polar8ear 2013-10-4 22:41:02 | 只看该作者
全局:
xusi 发表于 2013-10-2 01:46

Thanks you so much!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表