Leetcode 147. Insertion Sort List 插入排序 in Java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 147. Insertion Sort List 插入排序 in Java相关的知识,希望对你有一定的参考价值。

147. Insertion Sort List

  • Total Accepted: 80869
  • Total Submissions: 263074
  • Difficulty: Medium

 

Sort a linked list using insertion sort.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        
        if(head==null || head.next==null) return head;
    
        ListNode newHead=new ListNode(0);//后面使用tmp.next与pre比较,所以增加一个新的newHead
        
        ListNode cur=head;
        
        while(cur!=null){
            ListNode next=cur.next;//放这里而不放在循环末尾,防止out of index
            ListNode tmp=newHead;
            while(tmp.next!=null && tmp.next.val<cur.val){
                tmp=tmp.next;
            }
            cur.next=tmp.next;
            tmp.next=cur;
            cur=next;
  
        }
       return newHead.next;
    }
}

 

  

以上是关于Leetcode 147. Insertion Sort List 插入排序 in Java的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-147-Insertion Sort List

LeetCode 147. Insertion Sort List

Leetcode 147. Insertion Sort List 插入排序 in Java

leetcode 147 Insertion Sort List

Leetcode147. Insertion Sort List

LeetCode 147. Insertion Sort List