当前位置:   article > 正文

力扣HOT100 - 148. 排序链表

力扣HOT100 - 148. 排序链表

解题思路:

归并排序

  1. class Solution {
  2. public ListNode sortList(ListNode head) {
  3. if (head == null || head.next == null) return head;
  4. ListNode fast = head.next, slow = head;
  5. while (fast != null && fast.next != null) {
  6. slow = slow.next;
  7. fast = fast.next.next;
  8. }
  9. ListNode temp = slow.next;
  10. slow.next = null;
  11. ListNode left = sortList(head);
  12. ListNode right = sortList(temp);
  13. ListNode dum = new ListNode(0);
  14. ListNode cur = dum;
  15. while (left != null && right != null) {
  16. if (left.val < right.val) {
  17. cur.next = left;
  18. left = left.next;
  19. } else {
  20. cur.next = right;
  21. right = right.next;
  22. }
  23. cur = cur.next;
  24. }
  25. cur.next = left != null ? left : right;
  26. return dum.next;
  27. }
  28. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/490347
推荐阅读
相关标签
  

闽ICP备14008679号