牛骨文教育服务平台(让学习变的简单)

问题描述

有一个带头结点的单链表对其排序,使之递增有序。

算法思想

因为是单链表的一次排序,练习题12中采用的是插入排序的算法,同样类似,我们可以想到使用选择排序算法完成排序。选择排序一共分成两个部分,即查找最小值和将最小值结点插入合适的位置两个部分。具体算法如下:

算法描述

//查找最小值
LNode* FindMin(LNode* head)
{
    LNode *pre=head;
    LNode *premin=head;
    LNode *p=head->next;
    LNode *min=head->next;
    while(p){
        if(p->data<min->data){
            min=p;
            premin=pre;
        }
        pre=p;
        p=p->next;
    }
    return premin;
}
//将最小值插入合适位置
void SelctionSort(LNode *rear, LNode *premin)
{
    LNode *min=premin->next;
    if(min==NULL){
        return;
    }
    premin->next=min->next;
    min->next=rear->next;
    rear->next=min;
}

具体代码见附件。

附件

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

typedef int ElemType;
typedef struct LNode{
    ElemType data;
    struct LNode *next;
}LNode, *LinkList;

LinkList CreatList(LNode*);
LNode* FindMin(LNode*);
void SelctionSort(LNode*, LNode*);
void Print(LNode*);

int main(int argc,char* argv[])
{
    LNode *head;
    head=(LNode*)malloc(sizeof(LNode));
    head->next=NULL;

    head=CreatList(head);
    Print(head);

    LNode *premin=NULL;
    LNode *r=head;

    while(r){
        premin=FindMin(r);
        SelctionSort(r, premin);
        r=r->next;
    }
    Print(head);
    return 0;
}
//头插法建立单链表
LinkList CreatList(LNode *head)
{
    LNode *L;
    ElemType x;
    scanf("%d",&x);
    while(x!=999){
        L=(LNode*)malloc(sizeof(LNode));
        L->data=x;

        L->next=head->next;
        head->next=L;

        scanf("%d",&x);
    }
    return head;
}
//查找最小值
LNode* FindMin(LNode* head)
{
    LNode *pre=head;
    LNode *premin=head;
    LNode *p=head->next;
    LNode *min=head->next;
    while(p){
        if(p->data<min->data){
            min=p;
            premin=pre;
        }
        pre=p;
        p=p->next;
    }
    return premin;
}
//选择排序
void SelctionSort(LNode *rear, LNode *premin)
{
    LNode *min=premin->next;
    if(min==NULL){
        return;
    }
    premin->next=min->next;
    min->next=rear->next;
    rear->next=min;
}
//打印全部结点
void Print(LNode *head){
    LNode *p=head->next;
    while(p){
        printf("%4d",p->data);
        p=p->next;
    }
    printf("
");
}

注:选择排序与插入排序中,插入排序是将结点彻底取下来进行插入排序(即已造成断链),而选择排序中从头至尾都没有断链,中途只是暂时取下结点,然后及时插入到合适位置。