采用选择排序法对链表进行排序,注意交换操作中不是对链表里某一节点里的某一元素进行交换,而是对两节点指针的交换

来源:互联网 发布:淘宝如何设置货到付款 编辑:程序博客网 时间:2024/06/05 03:25

/*结构体定义*/

struct stu
{
    int StuID;//
    char name[10];//
    int sex;//
    int years;//
    struct stu *next;  
};

 

/***************************************************************
*   Function Name: SortList(struct stu *pHead)
*   Purpose: 对链表按学号进行排序
*   Inputs:
            1.pHead, 链表头指针
*   Outputs:
            NULL
*   Retrun Value: 返回int类型值
****************************************************************/
int SortList(struct stu *pHead)
{
    /*指针变量定义*/
    struct stu *pi = NULL;
    struct stu *pj = NULL;
    struct stu *psmall = NULL;
    struct stu *pafter = NULL;
    struct stu *piAfter = NULL;
    struct stu *pjAfter = NULL;
    struct stu *ptemp = NULL;
    struct stu *psmallAfter = NULL;

    piAfter = pHead;//目的是记住pi的上一个元素
    /*选择排序法*/
    for(pi = pHead->next; pi->next != NULL; pi = pi->next)
    {
        psmall = pi;
        for(pj = pi->next ; pj != NULL; psmallAfter = pj, pj = pj->next)//注意for循环的写法
        {           
            if(pj->StuID < psmall->StuID)
            {
                psmall = pj;
                pjAfter = psmallAfter;/*记住psmall的上一个元素*/
            }          
        }
        /*以下这种情况是当psmall指向的元素是链表最后一个元素时所进行的交换*/
        if(psmall->next == NULL)//这时pi肯定不等于psmall,因为pi到不了链表尾,最多是链表尾的前一个节点处
        {
            piAfter->next = psmall;
            psmall->next = pi->next;
            pjAfter->next = pi;
            pi->next = NULL;
        }
        else
        if(psmall != pi)
        {
            piAfter->next = psmall;
            pjAfter->next = pi;
            ptemp = psmall->next;//暂存
            psmall->next = pi->next;
            pi->next = ptemp;           
        }
/* 由于前面的地址交换,使得pi的值改变,这时回到第一层循环前应该将其还原到原来位置的下一个位置,
 * 由于有for语句的pi = pi->next,所以这里需要将pi还原为原来的位置
 */
        pi = piAfter->next;


        piAfter = piAfter->next;/*记住pi的上一个元素*/ 
    }
    return 0;
}

原创粉丝点击