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

单链表排序解决方法

2012-02-07 
单链表排序我写了个链表:#includestdio.h #includestring.h #defineN10extern_floatconvert#pragmaex

单链表排序
我写了个链表:
#include   "stdio.h "
#include   "string.h "
#define   N   10

extern   _floatconvert;
#pragma   extref   _floatconvert   /*Solve   the   problem   of   floating   scanf*/

typedef   struct   student
{
    int   num;
    char   name[20];
    char   gender;
    int   age;
    float   chinese;
    float   maths;
    float   english;
    float   aver;
    struct   student   *next;
}stu;


main()
{
    stu   *sort(stu   *);
    int   i;
    stu   *p,s[N]={{107, "xuhui ", 'm ',28,90.00,95.00,97.00},
                          {102, "jiangyi ", 'm ',25,92.00,95.00,96.00},
                          {103, "jiangchangwei ", 'm ',28,75.00,60.00,65.00},
                          {104, "wenkai ", 'm ',28,60.00,65.00,60.00},
                          {101, "huangqinyu ", 'f ',28,90.00,65.00,75.00}};
    for(p=s;p <s+N;p++)
    {
        p-> aver=(p-> chinese+p-> maths+p-> english)/3.00;
        p-> next=p+1;
    }
    p--;
    p-> next=NULL;
    p=sort(s);
    while(p)
    {
        printf( "%d   %s   %c   %d   %.2f   %.2f   %.2f   %.2f\n ",p-> num,p-> name,p-> gender,p-> age,p-> chinese,p-> maths,p-> english,p-> aver);
        p=p-> next;
    }
    getch();
}

stu   *sort(stu   *stud)
{
    stu   *head,*phead,*p4,*p1,*p2;
    phead=head=stud;
    p4=phead-> next;
    while(p4)
    {
        p2=head;
        while(p2-> aver> p4-> aver)   如果这里用aver(平均分),num,english都可得到
                                                          正确结果,
        {                                                 但用别的就不行(如maths),不知道是怎么回事,
            p1=p2;                                   望高手解答!
            p2=p2-> next;
        }
        if(p2!=p4)
        {
            phead-> next=p4-> next;
            if(p2==head)
            {
                p4-> next=p2;


                head=p4;
            }
            else
            {
                p1-> next=p4;
                p4-> next=p2;
            }
        }
        phead=p4;
        p4=p4-> next;
    }
    phead-> next=NULL;
    return(head);
}



[解决办法]
思路应该没有问题,这种单链表的头指针很麻烦,要特别处理
最好能加个空节点作为头,会简单很多
楼主可能细节出错

stu *head = stud;
stu *prev,*curr,*next; //previous-> current-> next
stu *temp;
curr = head;
if(curr==NULL || curr-> num==0)
return NULL;
prev = head;
next = curr-> next;
while((curr=next) && (curr-> num!=0)){
next = curr-> next;
if(curr-> item > = head-> item){ //current插到head前,previous不变
curr-> next = head;
head = curr;
prev-> next = next;
continue;
}

temp = head;
while(temp-> next-> item > curr-> item)
temp = temp-> next;
if(temp-> next != curr){ //current插到temp和temp-> next间
curr-> next = temp-> next;
temp-> next = curr;
prev-> next = next;
}else //不需插入操作
prev = curr;
}
return head;

热点排行