147. Insertion Sort List

题目分析

题目链接,登录 LeetCode 后可用
这道题目就是基于链表结构的插入排序。其中用到了一些常用的小技巧,比如用哑结点来消除头结点的特殊性。插入排序的时间复杂度为 O(n^2),空间复杂度为 O(1)。

代码

/**
 * 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 || head.next == null) {
        //     return head;
        // }
        
        ListNode dummy = new ListNode(0);
        
        while(head != null) {
            ListNode node = dummy;
            
            // 找到插入位置
            while(node.next != null && node.next.val < head.val) {
                node = node.next;
            }
            // 我们马上就要更新 head.next 的值,但是 head.next 的原有值我们遍历链表还要用,所以先用一个临时变量保存一下
            ListNode temp = head.next;
            head.next = node.next;
            node.next = head;
            head = temp;
        }
        
        return dummy.next;
    }
}

你可能感兴趣的:(147. Insertion Sort List)