链表相关算法

// 链表插入排序:
/**
 * 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
上一篇Wildcard Matching
下一篇dfs算法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭