一、题目叙述:
Sort a linked list using insertion sort.
二、解题思路:
Medium题,啊。。。我今天头晕脑胀,写的不太顺利。代码之混乱,我现在提交成功了都还很迷。
使用插入排序的方法对链表进行排序,即每次和前面的结点比找到合适的位置插入,链表不同于数组的地方在于,只能从前往后比,找到第一个比目前结点值大的结点,插入到这个结点前面即可。
思路:
(1)先注意链表为空及链表只是单结点的情况,直接返回头指针即可。
(2)从链表第二个结点开始往后循环, 每个结点i都与从头结点开始的各个结点j比较(此处为之后操作记录下i和j之前的结点remi,remj),碰到第一个值比其大的结点:创建与i值相同的新结点,把新节点放在j结点前,删掉i结点,重新定义i的位置,跳出循环,i指针后移。以此类推直至i为null。
三、源码:
public class Solution
{
public ListNode insertionSortList(ListNode head)
{
if (head == null || head.next == null) return head;
ListNode remi, remj;
ListNode i = head.next;
remi = head;
while (i != null)
{
remj = head;
ListNode j = head;
while (j != i)
{
if (j.val > i.val)
{
if (j == head)
{
ListNode frs = new ListNode(i.val);
frs.next = head;
remi.next = i.next;
head = frs;
i = remi;
}
else
{
ListNode frs = new ListNode(i.val);
remj.next = frs;
frs.next = j;
remi.next = i.next;
i = remi;
}
break;
}
remj = j;
j = j.next;
}
remi = i;
i = remi.next;
}
return head;
}
public static void main(String args[])
{
ListNode a = new ListNode(3);
ListNode first = a;
a.next = new ListNode(2);
a = a.next;
a.next = new ListNode(1);
//String a = "";
//String b = "";
// int[] digits = {0};
Solution solution = new Solution();
// int[][] abc = {{2}};
// int[] b = {2,3,4};
// for(int i = 0; i < abc.length; i ++)
ListNode res = solution.insertionSortList(first);
while (res != null)
{
System.out.print(res.val);
res = res.next;
}
}
}