Insertion Sort List | leetcode

Sort a linked list using insertion sort.


// Type your C++ code and click the "Run Code" button!
// Your code output will be shown on the left.
// Click on the "Show input" button to enter input data to be read (from stdin).

#include 
   
   
    
    
using namespace std;
#include 
    
    
     
     
#include 
     
     
      
      

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
 
class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if (head == NULL) {
            return NULL;
        }
        ListNode *cur = head->next; //第一个点已经排好序
        ListNode *result_head = head; //结尾链表的头结点,每次遍历的开始 
        ListNode *prev = head;
        while (cur) {
            ListNode *next = cur->next;
            //优化,如果cur大于prev,那么直接进入下一个节点
            if (cur->val >= prev->val) {
                prev = cur;
                cur = next;
                continue;
            }
            //找到一个比cur大的节点
            ListNode *tmp_cur = result_head;
            ListNode *tmp_prev = NULL;
            while (tmp_cur->val < cur->val) {
                tmp_prev = tmp_cur;
                tmp_cur = tmp_cur->next;
            }
            if (tmp_cur == cur) { //到达当前节点,不必排序,只更新prev节点即可
                prev = cur;
            }
            else {
                //断开当前节点
                prev->next = next;
                if (tmp_prev == NULL) { 
                    //插入到开始
                    cur->next = result_head;
                    result_head = cur;
                }
                else { //插入到tmp_prev的后面
                    cur->next = tmp_prev->next;
                    tmp_prev->next = cur;
                }
            }
            
            cur = next;
        }
        return result_head;
    }
};
int main() {
    
    Solution so;
    ListNode ln(10), ln1(2), ln2(-1), ln3(9), ln4(4);
    ln.next = &ln1;
    ln1.next = &ln2;
    ln2.next = &ln3;
    ln3.next = &ln4;
    ListNode *result = so.insertionSortList(&ln);
    while (result) {
        cout << result->val << " ";
        result = result->next;
    }
    
    return 0;
}

     
     
    
    
   
   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值