单链表实现插入排序

来源:互联网 发布:在淘宝上怎么修改评价 编辑:程序博客网 时间:2024/05/29 18:41

这里给出了一种单链表插入排序的实现。另一种类似的实现参见《C算法(第一卷:基础、数据结构、排序和搜索)(第三版)》程序3-11。

 

 

 

 

#include <stdio.h>
#include <stdlib.h>

 

typedef struct list LIST;
typedef LIST *link;

 

struct list
{
 int item;
 link next;
};

 

/*插入排序主例程*/

void InsertionSort(link h)
{
     link h1,h2,h3; /*h2用来指向需要插入的结点,h3用来指向h2的前一个结点*/
     for(h3=h,h2=h->next;h2!=NULL;)
    {
           h1=h; /*h1用来遍历寻找合适的插入位置*/
           for(;h1!=h2;h1=h1->next)
          {
                 if(h1->next->item > h2->item)/*如果找到,即把h2所指向的结点插到h1后面,然后跳出循环*/
                {
                   h3->next=h2->next;
                   h2->next=h1->next;
                   h1->next=h2;
                   h2=h3->next;
                   break; /*别忘了此处的break*/
                }
          }
 
          if(h1==h2)/*此处需要注意,只在h2所指结点不需要前插时,移动h2和h3*/
         {
              h2=h2->next;
              h3=h3->next;
         }
     }
}

 

/*单链表插入排序的测试例程*/

int main(void)
{

     /*构造一个包含头节点的单链表*/
     link head = malloc(sizeof *head);
     link p = head;
     int i=0;
     while(i<100)
    {
         p->next = malloc(sizeof *head);
         p = p->next;
         p->item = rand()%100;
         printf("%d ",p->item);
         p->next = NULL;
         i++;
    }
 
    printf("/n");
 

    /*插入排序*/
    InsertionSort(head);
 

    /*输出排序后的链表*/
    p=head->next;
    while(p!=NULL)
   {
       printf("%d ",p->item);
       p=p->next;
   }

 

   /*释放内存*/
    while(head)
   {
    p=head;
    head=head->next;
    free(p);
   }

  

    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

0 0