链表 插入排序

/**注意往链表头插入元素的情况
 * 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((head==NULL)||(head->next==NULL)) return head;
        ListNode *res=head;
        head = head->next;
        res->next=NULL;
       
        while(head){
            ListNode *p=res;
            while(p->next && (p->next->val) <= (head->val)){
               p=p->next;
            }
            if((p->val) > (head->val)){                  //这几个要注意顺序
                ListNode *temp = head->next;
                head->next=p;
                res=head;
                head=temp;
                
            }
            else{                                          //注意顺序
            
            ListNode *temp = p->next;
            p->next=head;
            head=head->next;
            p->next->next=temp;
            }
            
            }
        return res;
        }
};

 

posted @ 2015-07-21 19:58  *桔子*  阅读(179)  评论(0编辑  收藏  举报