Description
https://leetcode.com/problems/insertion-sort-list/
题目大意:
使用插入排序算法对链表进行排序。
Solving Ideas
插入排序
Solution
/**
* 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 resHead = head;
ListNode pPre = head;
ListNode pCur = head.next;
while (pCur != null) {
if (pCur.val < pPre.val) {
ListNode node = pCur;
pCur = pCur.next;
pPre.next = pCur;
if (resHead.val > node.val) {
//结点插入到原头结点之前
node.next = resHead;
resHead = node;
} else {
//插入到头结点之后
ListNode pNode = resHead;
while (pNode.next.val < node.val) pNode = pNode.next;
node.next = pNode.next;
pNode.next = node;
}
} else {
pPre = pCur;
pCur = pCur.next;
}
}
return resHead;
}
}