链表相关算法

// 链表插入排序:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {

        if( NULL == head || NULL == head->next )
        {
            return head;
        }

        ListNode *myHead = head;
      //  ListNode *cur = myHead;
        ListNode *p = head->next;
        myHead->next = NULL;
        ListNode *pre = NULL;
        ListNode *pCur = NULL;
        ListNode *pCurNext = NULL;

        for( pCur = p; pCur != NULL; pCur = pCurNext )
        {
            pCurNext = pCur->next;
            pCur->next = NULL;
            p = myHead;
            pre = NULL;

            while( p != NULL )
            {
                ListNode *pnext = p->next;

                if( pCur->val <= p->val )
                {
                    if( NULL == pre )            
                    {
                        pCur->next = myHead;
                        myHead = pCur;
                    }
                    else 
                    {
                        pCur->next = p;
                        pre->next = pCur;
                    }

                    break;
                }
                else
                {
                    pre = p;
                    p = pnext;
                }

            }

            if( NULL == p )
            {
                pre->next = pCur;
            }

        }

       return myHead;


    }
};

你可能感兴趣的:(goodCode)