Insertion Sort List

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) {
        ListNode helper = new ListNode(0);
        while(head != null) {
            ListNode node = helper;
            while(node.next != null && node.next.val < head.val) {
                node = node.next;
            }
            ListNode tem = head.next;
            head.next = node.next;
            node.next = head;
            head = tem;
        }
        return helper.next;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2276317