1. 程式人生 > 實用技巧 >對連結串列進行插入排序

對連結串列進行插入排序

對連結串列進行插入排序

題目:
示例 1:

輸入: 4->2->1->3
輸出: 1->2->3->4
示例 2:

輸入: -1->5->3->4->0
輸出: -1->0->3->4->5

解題思路:需要維護幾個引用來記錄當前已排序的和正在排序的節點,當找到大於當前要排序的節點值後進行插入操作

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode insertionSortList(ListNode head) {
        
        if(head == null)
            return null;
        
        if(head.next == null)
            return head;
        
        ListNode root = new ListNode(0);
        root.next = head;

        ListNode p = root.next;
        ListNode next = p.next;
        
        while(next != null) {
            
            System.out.println(p == null);
            if(p.val <= next.val) {
                p = p.next;
                next = p.next;
                continue ;
            }
            
            ListNode pr = root;
            while(pr.next.val <= next.val) {
                pr = pr.next;
            }
            
            p.next = next.next;
            next.next = pr.next;
            pr.next = next;
            next = p.next;
        }
        
        return root.next;
    }
}