147. Insertion Sort List(链表的插入排序)

Sort a linked list using insertion sort.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

所以就是在考insertion sort,AC代码:

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        ListNode dummy(0);
        ListNode* pre=&dummy;
        ListNode* cur=head;
        dummy.next=head;
        while(cur){
            if(cur->next&&cur->next->valval){
                while(pre->next&&pre->next->valnext->val){
                    pre=pre->next;
                }
                ListNode* tmp=pre->next;
                pre->next=cur->next;
                cur->next=cur->next->next;
                pre->next->next=tmp;
                pre=&dummy;
            }
            else{
                cur=cur->next;
            }
        }
        return dummy.next;
    }
};
看了别人的解答。。。。。亲自写还是有点难的。。(我好菜啊QUQ

你可能感兴趣的:(LeetCode)