单向链表排序——冒泡排序(C语言版)

LinkList* LinkListBubbleSort(LinkList* pHead)
{
    LinkList* pCurr = (LinkList *)NULL;
    LinkList* pPost = (LinkList *)NULL;
    LinkList* pFirst = (LinkList *)NULL;
    LinkList* pPrev = (LinkList *)NULL;
    unsigned int uwLinkListLength = 0;
    unsigned int uwInnerLoopIndex = 0;
    unsigned int uwOuterLoopIndex = 0;

    if (NULL == pHead)
    {
        return (LinkList *)NULL;
    }

    pFirst = (LinkList *)malloc(sizeof(LinkList));
    if (NULL == pFirst)
    {
        return (LinkList *)NULL;
    }
    
    uwLinkListLength = GetLinkListLength(pHead);
    uwOuterLoopIndex = uwLinkListLength;
    pFirst->m_next = pHead;

    while (uwOuterLoopIndex > 0)
    {
        pFirst->m_next = pHead;
        pCurr = pFirst->m_next;
        pPost = pCurr->m_next;

        uwInnerLoopIndex = uwOuterLoopIndex;
        while ((NULL != pPost) && (uwInnerLoopIndex > 0))
        {
            if (pCurr->m_key > pPost->m_key)
            {
                pFirst->m_next->m_next = pPost->m_next;
                pPost->m_next = pFirst->m_next;
                
                if (pHead == pFirst->m_next)
                {
                    pHead = pPost;
                    pPrev = pPost;
                }
                else
                {
                    pPrev->m_next = pPost;
                    pPrev = pPrev->m_next;
                }
                
                pPost = pCurr->m_next;
                pFirst->m_next = pCurr;

            }
            else
            {
                pPrev = pCurr;
                pCurr = pCurr->m_next;
                pPost = pCurr->m_next;
                pFirst->m_next = pCurr;
            }
            uwInnerLoopIndex--;
        }
        uwOuterLoopIndex--;
    }

    pFirst->m_next = NULL;
    free(pFirst);
    pFirst = NULL;
    return pHead;
}

你可能感兴趣的:(数据结构)