题目:
Sort a linked list using insertion sort.
思路:
- 这题比较简单,题干已经要求用插入排序对链表进行排序
- 将链表分为两个部分,一个部分已经排好序,就用head做头结点,另一部分待排序,用toSortList做头结点
- 令原来链表的一个node作为已排好序的唯一node赋给head
- 从第二个node开始都是待排序的,所以第二个node为待排序头结点toSortList
- 切断已排序和未排序的连接,即head.next = null
- 每次从待排序中取一个node准备插入已排序链表中,记为temp2
- 查看待插点temp2的值是否比head的值小,如果是,插到head前面
- temp1从head开始,遍历已排序链表,找到temp2应该插入的位置,插入
注意点:
- java中,类的属性可以迭代调用
- 例如,temp1.next.val可以读取temp1下一个元素的值
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode toSortList,temp1,temp2;
if (head == null){
return head;
}
toSortList = head.next;
head.next = null;
while (toSortList != null){
temp1 = head;
temp2 = toSortList;
toSortList = toSortList.next;
temp2.next = null;
if (temp2.val <= head.val){
temp2.next = head;
head = temp2;
continue;
}
while ((temp1.next != null) && (temp1.next.val < temp2.val)){
temp1 = temp1.next;
}
temp2.next = temp1.next;
temp1.next =temp2;
}
return head;
}
}