- 论坛徽章:
- 0
|
这段代码从0-999中抽取N个随机的整数,构造一个带表头节点的链表(第一个for循环),每个数字存放在一个节点里。
然后遍历链表(第二个for循环),按照存放的数字的大小,对节点排序。(例子里应该是从小到大的顺序)
在这里,构造了2个带表头节点的链表,一个是输入(无序),一个是输出(排序之后)。循环的每一次变换,就是从输入链表取出一个节点(删除),然后把它有序的插入输出链表。
觉得我的描述可能有出入的,可以看下面主程序区的原文注释部分。
代码使用下列声明:
- typedef struct node* link;
- struct node {int item; link next};
复制代码
接下来是主代码
- /* Program 3.II List insertion sort
- * This code generate N random integers between 0 and 999,
- * builds a linked list with one number per node(first for loop),
- * and then rearranges the nodes so that the numbers appear in order
- * when we traverse the list(second for loop).
- * To accomplish the sort, we maintain two lists, an input(unsorted) list
- * and an output(sorted) list. On each iteration of the loop,
- * we remove a node from the input and insert it into position in the output.
- */
- struct node heada, headb;
- link t,u,x,a=&heada,b;
- for (i=0,t=a;i<N;i++)
- {
- t->next=malloc(sizeof *t);
- t=t->next; t->next=NULL;
- t->item=rand() % 1000;
- }
- b=&headb; b->next=NULL;
- for (t=a->next;t!=NULL;t=u)
- {
- u=t->next;
- for (x=b;x->next!=NULL;x=x->next)
- if (x->next->item > t->item) break;
- t->next=x->next; x->next=t;
- }
复制代码
问题来了,这里似乎并没有在a指向的链表中作删除操作(a->next貌似还是指向---作了插入操作的节点(t)?)
是我理解错了,还是书上描述错了?我想了一个上午,现在头有点昏了。
//编辑一下,操作不会有问题,貌似不作操作也可以。昏死了,感觉应该把“remove”改成“fetch“比较合适吧?
[ 本帖最后由 imonyse 于 2007-5-8 10:59 编辑 ] |
|