zoukankan      html  css  js  c++  java
  • Insertion Sort List

    链表的插入排序算法,其中大循环是,从原始链表中挨个读取每个元素。

    取出的每个元素用插入排序建立新表即可

     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         ListNode * temp=head;  //用于最外层循环的控制。表述的是当前节点
    13         ListNode * tail;  
    14         ListNode * myhead=NULL;
    15         if(head==NULL)
    16             return NULL;
    17         while(temp!=NULL)
    18         {
    19             tail=temp->next;
    20             myhead=insertNode(myhead,temp);
    21             temp=tail;
    22         }
    23         return myhead;
    24     }
    25     ListNode * insertNode(ListNode * head,ListNode * temp)
    26     {
    27         temp->next=NULL;
    28         if(head==NULL)
    29             return temp;
    30         ListNode * t=head;
    31         ListNode * pre=NULL;
    32         while(t!=NULL)
    33         {
    34             if((temp->val)<(t->val))
    35             {
    36                 if(pre!=NULL)
    37                 {
    38                     pre->next=temp;
    39                 }
    40                 temp->next=t;
    41                 break;
    42             }
    43             pre=t;
    44             t=t->next;
    45             if(pre->next==NULL)
    46                 pre->next=temp;
    47                 
    48             
    49         }
    50         if(pre==NULL)
    51             head=temp;
    52         return head;
    53     }
    54 };
  • 相关阅读:
    自定义组件要加@click方法
    绑定样式
    647. Palindromic Substrings
    215. Kth Largest Element in an Array
    448. Find All Numbers Disappeared in an Array
    287. Find the Duplicate Number
    283. Move Zeroes
    234. Palindrome Linked List
    202. Happy Number
    217. Contains Duplicate
  • 原文地址:https://www.cnblogs.com/aguai1992/p/4628880.html
Copyright © 2011-2022 走看看