zoukankan      html  css  js  c++  java
  • LeetCode 147. Insertion Sort List

    原题链接在这里:https://leetcode.com/problems/insertion-sort-list/

    题目:

    Sort a linked list using insertion sort.

    题解:

    Sort List类似. 

    当出现cur.val > cur.next.val时就需要insert cur.next到对应位置.

    Time Complexity: O(n^2). Space: O(1).

    AC Java:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution {
    10     public ListNode insertionSortList(ListNode head) {
    11         if(head == null || head.next == null){
    12             return head;
    13         }
    14         
    15         ListNode dummy = new ListNode(0);
    16         dummy.next = head;
    17         
    18         while(head.next != null){
    19             if(head.val > head.next.val){ //当出现前一个点val 比后一个点val大时,就要找到添加位置
    20                 ListNode mark = dummy;
    21                 while(mark.next != null && mark.next.val<head.next.val){ //找mark位置
    22                     mark = mark.next;
    23                 }
    24                 
    25                 ListNode temp = head.next;
    26                 head.next = head.next.next;
    27                 temp.next = mark.next;
    28                 mark.next = temp;
    29             }else{
    30                 head = head.next;
    31             }
    32         }
    33         
    34         return dummy.next;
    35     }
    36 }
  • 相关阅读:
    表达式for loop
    用户输入
    字符编码
    变量字符编码
    Python安装
    Python 2 or 3?
    Python解释器
    2017中国大学生程序设计竞赛
    Educational Round 27
    Round #429 (Div.2)
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825000.html
Copyright © 2011-2022 走看看