/**
* 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 tmpHead = insertionSortList(head.next);
if(head.val <= tmpHead.val){ // 如果两个节点相等,则插入到已存在节点的前面
head.next = tmpHead;
return head;
}else{
ListNode tmpHead2 = tmpHead;
// 找到合适的位置的前一个节点
while(tmpHead2.next != null && tmpHead2.next.val < head.val){
tmpHead2 = tmpHead2.next;
}
// 将head连接到链表中
ListNode b = tmpHead2.next;
tmpHead2.next = head;
head.next = b;
return tmpHead;
}
}
}
// 头插法
/**
* 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 dummy = new ListNode();
dummy.next = head;
ListNode cur = head;
while(cur.next != null){
ListNode newcur = dummy;
while(true){
if(newcur.next == cur.next){
cur = cur.next;
break;
}
if(newcur.next.val >= cur.next.val){
ListNode curNext = cur.next;
// 先给cur.next节点从链表中提取出来
cur.next = cur.next.next;
// 将cur.next连接到newcur.next上
ListNode tmpNext = newcur.next;
newcur.next = curNext;
newcur.next.next = tmpNext;
break;
}else{
newcur = newcur.next;
}
}
}
return dummy.next;
}
}