147. Insertion Sort List

题目

原始地址:https://leetcode.com/problems/insertion-sort-list/#/description

/**
 * 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) {
        
    }
}

描述

使用插入排序给链表排序。

分析

该题目比较考查链表基本操作。链表的插入排序不同于数组,由于不能按照index访问,所以查找插入位置时不能使用二分查找,只能从头顺序遍历。注意插入时指针的引用操作。

解法

/**
 * 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) {
        ListNode dummy = new ListNode(0), curr = dummy;
        dummy.next = head;
        while (curr.next != null) {
            ListNode l = dummy;
            while (l.next != curr.next && l.next.val < curr.next.val) {
                l = l.next;
            }
            if (l != curr) {
                ListNode tmp = curr.next.next;
                curr.next.next = l.next;
                l.next = curr.next;
                curr.next = tmp;
            } else {
                curr = curr.next;
            }
        }
        return dummy.next;
    }
}
posted @ 2017-05-06 11:07  北冥尝有鱼  阅读(79)  评论(0编辑  收藏  举报