• Insertion Sort List


    Sort a linked list using insertion sort.

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *insertionSortList(ListNode *head) 
    12     {
    13         
    14         if(head == NULL || head->next == NULL)
    15             return head;
    16         
    17         vector<int> vec;
    18         ListNode *p = head;
    19         while(p != NULL)
    20         {
    21             vec.push_back(p->val);
    22             p = p->next;
    23         }
    24         
    25         for(int i = 1; i < vec.size(); i++)
    26         {
    27             int tmp = vec[i];
    28             int j;
    29             for(j = i; j > 0 && tmp < vec[j-1]; j--)
    30                 vec[j] = vec[j-1];
    31                 
    32             vec[j] = tmp;
    33         }
    34         
    35         p = head;
    36         for(vector<int>::iterator it = vec.begin(); it != vec.end(); it++, p = p->next)
    37             p->val = *it;
    38             
    39         return head;
    40     }
    41 };
  • 相关阅读:
    微信小程序
    js
    js
    uni
    uni/微信小程序
    uni/微信小程序
    ES6...扩展运算符(数组或类数组对象)
    微信小程序
    微信小程序
    玩转storm
  • 原文地址:https://www.cnblogs.com/YQCblog/p/3970210.html
Copyright © 2020-2023  润新知