问题:
Sort a linked list using insertion sort.
解决:
① 链表插入排序。
/**
* Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { //46ms public ListNode insertionSortList(ListNode head) { if(head == null || head.next == null) return head; ListNode header = new ListNode(Integer.MIN_VALUE); header.next = head; ListNode cur = head.next; head.next = null; while(cur != null){ ListNode tmp = header; while(tmp.next != null && tmp.next.val <= cur.val){ tmp = tmp.next; } ListNode next = cur.next; cur.next = tmp.next; tmp.next = cur; cur = next; } return header.next; } }② 在discuss中看到的,类似于归并排序,将链表分为前后两个链表,然后通过比较依次插入到链表中。
class Solution {
public ListNode insertionSortList(ListNode head) { if(head == null || head.next == null) return head; //链表对折 ListNode slow = head;//用于表示后半部分 ListNode fast = head;//用于记数 ListNode tmp = null;//tmp临时存储(类似pre) while(fast != null && fast.next != null){ tmp = slow; slow = slow.next; fast = fast.next.next; } ListNode l2 = insertionSortList(slow);//递归使后半部分有序 tmp.next = null;//断开链表,将其分为两部分 ListNode l1 = insertionSortList(head);//递归使前半部分有序 ListNode header = new ListNode(-1); ListNode cur = header; //将前半部分和后半部分比较 while(l1 != null && l2 != null){ if (l1.val < l2.val) { cur.next = l1; l1 = l1.next; }else{ cur.next = l2; l2 = l2.next; } cur = cur.next; } if(l1 != null) cur.next = l1; if(l2 != null) cur.next = l2; return header.next; } }