cherrychenlee

导航

 

原文地址:https://www.jianshu.com/p/245a71670d37

时间限制:1秒 空间限制:32768K

题目描述

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) {}
 * };
 */
class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        if(head==nullptr || head->next==nullptr)
            return head;
        ListNode tmp(0);
        ListNode* cur=head;
        while(cur){
            ListNode* next=cur->next;//保存下一个节点
            ListNode* pre=&tmp;
            while(pre->next&&(pre->next->val<cur->val)){
                pre=pre->next;
            }
            cur->next=pre->next;
            pre->next=cur;
            cur=next;
        }
        return tmp.next;
    }
};

运行时间:57ms
占用内存:968k

posted on 2019-05-08 14:08  cherrychenlee  阅读(99)  评论(0编辑  收藏  举报