免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2631 | 回复: 1
打印 上一主题 下一主题

[算法] [请教]Robert Sedgewick那本书里面一个链表插入排序算法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-05-08 10:56 |只看该作者 |倒序浏览
这段代码从0-999中抽取N个随机的整数,构造一个带表头节点的链表(第一个for循环),每个数字存放在一个节点里。
然后遍历链表(第二个for循环),按照存放的数字的大小,对节点排序。(例子里应该是从小到大的顺序)

在这里,构造了2个带表头节点的链表,一个是输入(无序),一个是输出(排序之后)。循环的每一次变换,就是从输入链表取出一个节点(删除),然后把它有序的插入输出链表。
觉得我的描述可能有出入的,可以看下面主程序区的原文注释部分。

代码使用下列声明:

  1. typedef struct node* link;
  2. struct node {int item; link next};
复制代码

接下来是主代码

  1. /* Program 3.II List insertion sort
  2. * This code generate N random integers between 0 and 999,
  3. * builds a linked list with one number per node(first for loop),
  4. * and then rearranges the nodes so that the numbers appear in order
  5. * when we traverse the list(second for loop).
  6. * To accomplish the sort, we maintain two lists, an input(unsorted) list
  7. * and an output(sorted) list. On each iteration of the loop,
  8. * we remove a node from the input and insert it into position in the output.
  9. */

  10. struct node heada, headb;
  11. link t,u,x,a=&heada,b;

  12. for (i=0,t=a;i<N;i++)
  13.         {
  14.          t->next=malloc(sizeof *t);
  15.          t=t->next; t->next=NULL;
  16.          t->item=rand() % 1000;
  17.         }

  18. b=&headb; b->next=NULL;
  19. for (t=a->next;t!=NULL;t=u)
  20.         {
  21.          u=t->next;
  22.          for (x=b;x->next!=NULL;x=x->next)
  23.                 if (x->next->item > t->item) break;
  24.          t->next=x->next; x->next=t;
  25.         }
复制代码


问题来了,这里似乎并没有在a指向的链表中作删除操作(a->next貌似还是指向---作了插入操作的节点(t)?)

是我理解错了,还是书上描述错了?我想了一个上午,现在头有点昏了。

//编辑一下,操作不会有问题,貌似不作操作也可以。昏死了,感觉应该把“remove”改成“fetch“比较合适吧?

[ 本帖最后由 imonyse 于 2007-5-8 10:59 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2007-05-08 11:27 |只看该作者
原帖由 imonyse 于 2007-5-8 10:56 发表
这段代码从0-999中抽取N个随机的整数,构造一个带表头节点的链表(第一个for循环),每个数字存放在一个节点里。
然后遍历链表(第二个for循环),按照存放的数字的大小,对节点排序。(例子里应该是从小到大的顺 ...


把a中的结点移到b中而已
删除是没有必要的,要不然你也得再分配
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP