原题地址:https://leetcode-cn.com/problems/insertion-sort-list/
题目描述:
对链表进行插入排序。
插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。
插入排序算法:
插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
重复直到所有输入数据插入完为止。
示例 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 || head.next == null)
return head;
ListNode cur = head.next, ar = head, pre = head, cur_pre = head;
while(cur != null)
{
while(ar != cur && ar.val <= cur.val)
{
pre = ar;
ar = ar.next;
}
if(ar != cur)
{
cur_pre.next = cur.next;
cur.next = ar;
if(ar != head)
pre.next = cur;
else
head = cur;
cur = cur_pre.next;
}
else
{
cur_pre = cur;
cur = cur.next;
}
ar = head;
}
return head;
}
}
希尔:
/**
* 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 lo = head, hi = head, mid = head;
while(hi.next != null && hi.next.next != null)
{
mid = mid.next;
hi = hi.next.next;
}
hi = mid.next;
mid.next = null;
ListNode i = insertionSortList(lo);
ListNode j = insertionSortList(hi);
ListNode n_head = new ListNode(-1);
ListNode k = n_head;
while(i != null || j != null)
{
if(i == null)
{
k.next = j;
break;
}
else if(j == null)
{
k.next = i;
break;
}
else if(i.val < j.val)
{
k.next = i;
k = k.next;
i = i.next;
}
else
{
k.next = j;
k = k.next;
j = j.next;
}
}
return n_head.next;
}
}