对链表进行插入排序。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        } 
        ListNode node1 = head;
        ListNode node2 = head.next;
        ListNode cur = new ListNode(0);
        cur.next = head;
        
        while(node2 != null){
            if(node1.val < node2.val){
                node1 = node1.next;
                node2 = node2.next;
            }else{
                node1.next = node2.next;
                ListNode f = cur;
                
                while(f.next.val < node2.val){
                    f = f.next;
                }
                node2.next = f.next;
                f.next = node2;
                node2 = node1.next;
            }
        }
        return cur.next;
    }
}

 

posted @ 2019-07-15 16:02  紫色的雪  阅读(207)  评论(0)    收藏  举报