Insertion Sort List

来源:互联网 发布:ubuntu删除谷歌输入法 编辑:程序博客网 时间:2024/05/21 08:58

1.题目

用插入排序对链表排序

Given 1->3->2->0->null, return 0->1->2->3->null

2.算法

这道题是指定实现插入排序。插入排序是一种O(n^2)复杂度的算法,基本思想就是每次循环找一个元素在当前排好序的结果中的相对位置,然后插入进去

对链表进行插入排序的正确方法是:新建一个头节点,遍历原来的链表,对原链表的每个节点找到新链表中适合插入位置的前指针,然后执行插入操作。
这种操作链表的题有一个技巧就是新建一个dummy作为head,然后把数据插入到dummy的链表中,最后返回dummy.next。

    public ListNode insertionSortList(ListNode head) {        // write your code here    if (head == null)    {    return null;    }    ListNode helper = new ListNode(0);    ListNode pre = helper;    ListNode cur = head;    while (cur != null)    {    ListNode next = cur.next;    pre = helper;            // 找插入位置    while (pre.next != null && pre.next.val <= cur.val)    {    pre = pre.next;    }    //把节点插入对应位置    cur.next = pre.next;    pre.next = cur;    cur = next;    }    return helper.next;    }


0 0