0
点赞
收藏
分享

微信扫一扫

147. 对链表进行插入排序

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        if(!head)
            return head;
        ListNode *newHead = new ListNode(-5001, head);
        ListNode *left = head, *right = head -> next;
        while(right){
            if(left -> val <= right -> val){    //如果默认有序则往后找
                left = left -> next;
            }
            else{
                ListNode *temp = newHead;   //链表涉及到插入肯定要引入临时节点
                while(temp -> next -> val <= right -> val)  //如果有序则往后找
                    temp = temp -> next;
                left -> next = right -> next;   //把right从原链表中删除
                right -> next = temp -> next;   //right指向temp的next
                temp -> next = right;   //temp指向right,实现插入
            }
            right = left -> next;   //继续往后找逆序的节点
        }
        return newHead -> next;
    }
};

Accepted
19/19 cases passed (16 ms)
Your runtime beats 72.9 % of cpp submissions
Your memory usage beats 98.92 % of cpp submissions (9.2 MB)

举报

相关推荐

0 条评论