首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

大家帮忙看看解决思路

2012-02-10 
大家帮忙看看#includestdio.h#includestdlib.h#defineLENsizeof(structnode)structnode{intnumstruct

大家帮忙看看
#include   <stdio.h>
#include   <stdlib.h>
#define   LEN   sizeof(   struct   node   )
struct   node
{
int   num;
struct   node   *next;
};

struct   node   *create()
{
struct   node   *p,   *q,   *head;
int   num;
head   =   (   struct   node   *)malloc(   LEN   );
head-> next   =   NULL;
p   =   head;
scanf(   "%d ",   &num   );
while(   num   !=   0   )
{
q   =   (   struct   node   *)malloc(   LEN   );
q-> num   =   num;
q-> next   =   NULL;
p-> next   =   q;
p   =   q;
scanf(   "%d ",   &num   );
}
return   (   head   );
}

void   print(   struct   node   *head   )
{
struct   node   *p;
p   =   head-> next;
while(   p   !=   NULL   )
{
printf(   "%-3d ",   p-> num   );
p   =   p-> next;
}
}
int   main()
{
struct   node   *head;
head   =   create();
print(   head   );
printf(   "\n "   );
system(   "pause "   );
return   0;
}
这是我写的新建链表,打印链表的程序。现在我想再写个函数来对新建的链表排序,然后再打印出来。就是在int   main()
{
struct   node   *head;
head   =   create();
                  head   =   sort();------------>   这里添加一个排序函数。
print(   head   );
printf(   "\n "   );
system(   "pause "   );
return   0;
}
请问这个该怎么写?

[解决办法]
插入排序
struct node *sort(struct node *head){
struct node *p, *q, *temp;
p = head-> next;
if(!p)return head;
while(p-> next){
q = head;
while(q-> next-> num < p-> next-> num)
q = q-> next;
if(q != p){
temp = q-> next;
q-> next = p-> next;
p-> next = p-> next-> next;
q-> next-> next = temp;
}
else
p = p-> next;
}
return head;
}
[解决办法]
void sort(struct node *head)
{
struct node *p, *q, Temp;

p = head-> next;
while( p != NULL )
{
q = p-> next;
while ( q != NULL )
{
if (p-> num > q-> num)
{
Temp.num = p-> num;
p-> num = q-> num;
q-> num = Temp.num;
}
q = q-> next;
}
p = p-> next;
}
}

排序的方法有很多种,这里只是一种比较常见的排序方法

热点排行