当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
2015年计算机等级考试二级C语言辅导实例编程(17)
发布时间:2011/1/16 18:21:00 来源:城市学习网 编辑:ziteng

  单链表冒牌排序

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

  01 #include

  02 #include

  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  [NextPage] 

  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

  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;

 [NextPage]

  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 }

广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved