题目描述
Sort a linked list using insertion sort.
解题思路:
插入排序的思想,初始输出链表为空,然后遍历输入的链表,记每个访问的节点为cur
1 如果输出链表为空,则直接插入cur
2 如果输出链表的头节点的值 > cur.val 则将cur作为输出链表的新的头
3 如果输出链表的尾节点的值 < cur.val 则直接插入cur
4 从尾往前扫输出链表,遇到输出链表扫到的节点的值 < cur.val 则将cur插入
/**
* 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 nHead = null, cur = null;
while (head != null) {
if (nHead == null) {
nHead = new ListNode(head.val);
cur = nHead;
} else {
if (cur.val <= head.val) {
cur.next = new ListNode(head.val);
cur = cur.next;
} else {
ListNode tmp = nHead, preTmp = null, c;
while (tmp.val < head.val) {
preTmp = tmp;
tmp = tmp.next;
}
c = new ListNode(head.val);
if (preTmp == null) {
c.next = nHead;
nHead = c;
} else {
c.next = tmp;
preTmp.next = c;
}
}
}
head = head.next;
}
return nHead;
}
}