题目链接:https://leetcode.com/problems/insertion-sort-list/

题目:

Sort a linked list using insertion sort.

思路:

头插法。用头结点可以简化插入链表时候的操作,因为要考虑插入链表中间和表头两种情况,插入表头时,head就要更新,还要判断pre指针是否为空

算法:

public ListNode insertSortList(ListNode head, ListNode t) {
		ListNode p = head.next, pre = head;// p t pre
		while (p != null && p.val < t.val) {
			pre = p;
			p = p.next;
		}
		t.next = p;
		pre.next = t;
		return head;
	}

	public ListNode insertionSortList(ListNode head) {
		ListNode p = head, tmp = p;
		ListNode newHead = new ListNode(0); //头结点
		while (p != null) {
			tmp = p;
			p = p.next;
			newHead = insertSortList(newHead, tmp);
		}
		return newHead.next;
	}