LeetCode 147. 对链表进行插入排序

题目描述:

解法一(头节点另处理):

/**
 * 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* pre=head, *cur=head->next;
        while(cur!=NULL){
            ListNode* pp=NULL,*nn=head;
            while(nn!=cur&&nn->val<=cur->val){            //寻找插入位置
                pp=nn;
                nn=nn->next;
            }
            if(nn==cur){                                  //原位置不变
                pre=cur;
                cur=cur->next;
            }
            else{
                pre->next=cur->next;                     //取出结点
                if(nn==head){                            //头节点另处理
                    cur->next=nn;
                    head=cur;
                }
                else{                                    //正常插入
                    cur->next=nn;
                    pp->next=cur;
                }
                cur=pre->next;
            }
            
        }
        return head;
    }
};

解法二(虚拟头节点):

/**
 * 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* Vhead=new ListNode(1);
        Vhead->next=head;
        ListNode* pre=head, *cur=head->next;
        while(cur!=NULL){
            ListNode* pp=Vhead,*nn=pp->next;
            while(nn!=cur&&nn->val<=cur->val){            //寻找插入位置
                pp=nn;
                nn=nn->next;
            }
            if(nn==cur){                                  //原位置不变
                pre=cur;
                cur=cur->next;
            }
            else{
                pre->next=cur->next;                     //取出结点
                cur->next=nn;
                pp->next=cur;
                cur=pre->next;
            }
        }
        head=Vhead->next;
        delete Vhead;
        return head;
    }
};
原文地址:https://www.cnblogs.com/oneDongHua/p/14264009.html