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

    Insertion Sort List

    Sort a linked list using insertion sort.

    这道题用两个链表做的,这样方便一点。还有新链表头结点我没有存放内容,这样也比较方便,后面返回head1.next就好了

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode insertionSortList(ListNode head) {
    14         ListNode head1 = new ListNode(0);
    15         if(null == head || null == head.next)
    16             return head;
    17         
    18         else{            
    19             ListNode temp = new ListNode(0);
    20             temp.val = head.val;
    21             temp.next = null;
    22             head1.next = temp;//用一个新链表
    23             
    24             ListNode ptr = head.next;
    25             while(ptr != null){        //遍历原来的链表,插入到新链表中
    26                 temp = head1.next;
    27                 ListNode tempPre = head1;            //temp前面的节点
    28                 while(temp != null){
    29                     if(temp.val > ptr.val){            //在temp前面插入结点
    30                         ListNode nodeAdd = new ListNode(0);
    31                         nodeAdd.val = ptr.val;
    32                         nodeAdd.next = temp;
    33                         tempPre.next = nodeAdd;
    34                         break;                        //插入完成,跳出循环
    35                     }
    36                     temp = temp.next;
    37                     tempPre = tempPre.next;
    38                 }
    39                 if(null == temp){                    //在新链表添加节点
    40                     ListNode nodeAdd = new ListNode(0);
    41                     nodeAdd.val = ptr.val;
    42                     nodeAdd.next = null;
    43                     tempPre.next = nodeAdd;
    44                 }
    45                 ptr = ptr.next;
    46             }
    47         }
    48         
    49         return head1.next;
    50     }
    51 }
  • 相关阅读:
    zabbix-agent报错记录
    远程执行命令恢复
    触发器例子
    自定义监控项
    监控项更新间隔
    python paramiko登陆设备
    python爬取某站磁力链
    python网络编程
    并发爬取网站图片
    Pandas Series和DataFrame的基本概念
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4119865.html
Copyright © 2011-2022 走看看