leetcode No147. Insertion Sort List

Question:

Sort a linked list using insertion sort.

Algorithm:

新建一个链表,模仿插入排序的过程

Accepted Code:

/**
 * 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) {
        ListNode* curHead=new ListNode(INT_MIN);   //避免对头结点操作
        if(head==NULL || head->next==NULL)
            return head;
        ListNode* pNode=head;      //遍历head的结点
        while(pNode){
            ListNode* tmp=pNode->next;  //pNode是要插入的结点,tmp要保存pNode->next;
            ListNode* pPre=curHead;     //插入点前结点
            ListNode* pNext=curHead->next;  //插入点后结点
            while(pNext && (pNext->val<pNode->val)){
                pPre=pPre->next;
                pNext=pNext->next;
            }
            pPre->next=pNode;
            pNode->next=pNext;
            pNode=tmp;
        }
        return curHead->next;
    }
};



你可能感兴趣的:(LeetCode,链表)