zoukankan      html  css  js  c++  java
  • leetcode 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)//only 0,1nodes
    15     {
    16         return    head;
    17     }
    18 
    19     ListNode    *pNode=head->next,*hNode=head,*tNode=NULL;
    20     hNode->next=NULL;
    21     while(pNode)
    22     {
    23         hNode=head;
    24 
    25     
    26 
    27       // find where to insert
    28       while (hNode)
    29       {
    30           if (hNode->val>pNode->val)//插入头结点之前
    31           {
    32               tNode=pNode->next;
    33               pNode->next=hNode;
    34               head=pNode;
    35               hNode=head;
    36               pNode=tNode;
    37               break;
    38           }
    39           else if (hNode->next==NULL)//到了最后一个节点
    40           {
    41               tNode=pNode->next;
    42               hNode->next=pNode;
    43               pNode->next=NULL;
    44               pNode=tNode;
    45               break;
    46           }
    47           else if (hNode->next->val>pNode->val)
    48           {
    49               tNode=pNode->next;
    50               pNode->next=hNode->next;
    51               hNode->next=pNode;
    52               pNode=tNode;
    53               break;
    54           }
    55           else
    56           {
    57               hNode=hNode->next;
    58           }
    59         
    60       }
    61 
    62     }
    63     
    64     return head;
    65     }
    66 };
  • 相关阅读:
    数组的地址和vector数组的地址
    字节跳动 测试开发工程师 面经
    最短路径树
    SPFA
    树的直径
    树的重心
    CF1401D Maximum Distributed Tree
    期望简述
    CF723E One-Way Reform
    CF1409E Two Platforms
  • 原文地址:https://www.cnblogs.com/karcylee/p/3989607.html
Copyright © 2011-2022 走看看