zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    NYOJ458
    NYOJ67
    NYOJ105
    NYOJ1071
    NYOJ463
    C语言练字用小软件 — Practise_Calligraphy_1.0(ANSI)
    NYOJ276
    NYOJ455
    NYOJ74
    Jzoj4458 密钥破解——Pollard-rho
  • 原文地址:https://www.cnblogs.com/YQCblog/p/3970210.html
Copyright © 2011-2022 走看看