题目描述
Sort a linked list using insertion sort.
一般思路(直接在原链表上进行插排)
很好理解,就是遍历每个结点cur,同时记录其前一个结点pre。
如果碰到某个cur的值小于pre,从头结点开始遍历,直到找到应该插入的位置。
不使用哑结点的问题就是多判断了一个cur要替换头结点,头结点往后移的状况,这时不能用遍历的代码
需要额外写一种情况
if(head.val > cur.val){
cur.next = head;
head = cur;
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public static ListNode insertionSortList(ListNode head) {
if(head == null || head.next &#