一、题目内容

image.png

二、题解

解法1:

思路

链表归并排序

代码

  1. public class Solution {
  2. /**
  3. * 归并排序
  4. *
  5. * @param head
  6. * @return
  7. */
  8. public ListNode sortInList(ListNode head) {
  9. // write code here
  10. if (head == null || head.next == null) {
  11. return head;
  12. }
  13. ListNode fast = head.next;
  14. ListNode slow = head;
  15. while (fast != null && fast.next != null) {
  16. fast = fast.next.next;
  17. slow = slow.next;
  18. }
  19. ListNode next = slow.next;
  20. slow.next = null;
  21. ListNode left = sortInList(head);
  22. ListNode right = sortInList(next);
  23. ListNode h = new ListNode(0);
  24. ListNode res = h;
  25. while (left != null && right != null) {
  26. if (left.val < right.val) {
  27. h.next = left;
  28. left = left.next;
  29. } else {
  30. h.next = right;
  31. right = right.next;
  32. }
  33. h = h.next;
  34. }
  35. h.next = left != null ? left : right;
  36. return res.next;
  37. }
  38. }