以文本方式查看主题

-  计算机科学论坛  (http://bbs.xml.org.cn/index.asp)
--  『 C/C++编程思想 』  (http://bbs.xml.org.cn/list.asp?boardid=61)
----  C语言中的单链表冒牌排序  (http://bbs.xml.org.cn/dispbbs.asp?boardid=61&rootid=&id=88564)


--  作者:葛靖青001
--  发布时间:12/7/2010 3:27:00 PM

--  C语言中的单链表冒牌排序
【转自互联网】

今天做链表排序有个误区,就是以为交换的时候要连next节点也交换,还要固定head节点,想了很久也没做出来,但是后来看网上的提示,才知道只要交换节点内的数据就可以了,根本不用交换next节点

  01 #include <stdio.h>

  02 #include <stdlib.h>

  03

  04 struct node

  05 {

  06     int data;

  07     struct node *next;

  08 };

  09

  10 struct node *create_list(int a[],int len)

  11 {

  12     struct node *phead;

  13     struct node *ptr;

  14     struct node *pre;

  15     phead=(struct node *)malloc(sizeof(struct node));

  16     int i=0;

  17     phead->data=a[i];

  18     phead->next=NULL;

  19     ptr=phead->next;

  20     pre=phead;

  21     for(i=1;i<len;i++)

  22     {

  23         ptr=(struct node *)malloc(sizeof(struct node));

  24         ptr->data=a[i];

  25         ptr->next=NULL;

  26         pre->next=ptr;

  27         ptr=ptr->next;

  28         pre=pre->next;

  29     }

  30

  31     return phead;

  32 }

  33

  34 void print_list(struct node *phead)

  35 {

  36     struct node *ptr=phead;

  37

  38     while(ptr != NULL)

  39     {

  40         printf("%d ",ptr->data);

  41         ptr=ptr->next;

  42     }

  43

  44     printf("\n");

  45 }

  46

  47 struct node *bubble(struct node *phead,int len)

  48 {

  49     struct node *ptr,*next;

  50     int temp;

  51

  52     for(int i=0;i<len;i++)

  53     {

  54         ptr=phead;

  55         next=ptr->next;

  56         for(int j=len-i-1;j>0;j--)

  57         {

  58             if(ptr->data > next->data)

  59             {

  60                 temp=ptr->data;

  61                 ptr->data=next->data;

  62                 next->data=temp;

  63             }

  64             ptr=ptr->next;

  65             next=next->next;

  66         }

  67     }

  68

  69     return phead;

  70 }

  71

  72 int main()

  73 {

  74     int a[10]={

  75         5,3,6,8,9,6,5,4,2,7

  76     };

  77

  78     struct node *phead;

  79     phead=create_list(a,10);

  80

  81     print_list(phead);

  82

  83     phead=bubble(phead,10);

  84

  85     print_list(phead);

  86 }


W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
42.969ms