• leetcodeTop(100) 31链表排序


    // 排序链表
    //给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 
    1. package Top31_40;
    2. import Util.ListNode;
    3. import java.util.ArrayList;
    4. import java.util.List;
    5. // 排序链表
    6. //给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
    7. public class Top31 {
    8. // 方法一 转换数组排序之后再创建链表 时间复杂度和空间复杂度都是O(n)
    9. public static ListNode sortList(ListNode head) {
    10. if (head == null) {
    11. return null;
    12. }
    13. List<ListNode> nodes = new ArrayList<>();
    14. ListNode cur = head;
    15. while (cur != null) {
    16. nodes.add(cur);
    17. cur = cur.next;
    18. }
    19. nodes.sort((s1, s2) -> (s1.val - s2.val));
    20. ListNode head2 = nodes.get(0);
    21. cur = head2;
    22. for (int i = 1; i <= nodes.size(); i++) {
    23. if (i == nodes.size()) {
    24. cur.next = null;
    25. return head2;
    26. }
    27. cur.next = nodes.get(i);
    28. cur = cur.next;
    29. }
    30. return head2;
    31. }
    32. //方法二 快排
    33. public ListNode fastSortList(ListNode head) {
    34. //边界
    35. if (head == null || head.next == null) return head;
    36. //伪头结点
    37. ListNode pre = new ListNode(0, head);
    38. //快排
    39. quickSort(pre, null);
    40. //返回头结点
    41. return pre.next;
    42. }
    43. //输入时伪头结点和尾节点null
    44. void quickSort(ListNode pre, ListNode end) {
    45. //如果节点数小于1就返回
    46. if (pre == end || pre.next == end || pre.next.next == end) return;
    47. //选第一个节点为基准
    48. ListNode b = pre.next;
    49. //建立临时链表
    50. ListNode cur = new ListNode(0);
    51. //临时左右两指针
    52. ListNode r = b, l = cur;
    53. //遍历,右指针下一节点为end,说明当前是最后一个元素,结束
    54. while (r.next != end) {
    55. //如果当前元素小于基准,就加入临时链表,并在原链表中删除
    56. if (r.next.val < b.val) {
    57. l.next = r.next;
    58. l = l.next;
    59. r.next = r.next.next;
    60. } else {
    61. //不小于基准,右指针后移
    62. r = r.next;
    63. }
    64. }
    65. //临时链表接在原链表前面,并把伪头结点指向临时节点头结点
    66. l.next = pre.next;
    67. pre.next = cur.next;
    68. //对基准的左右两边递归,注意输入都是伪头结点和两链表的尾节点的下一节点
    69. quickSort(pre, b);
    70. quickSort(b, end);
    71. }
    72. public static void main(String[] args) {
    73. int[] nums = {4, 2, 1, 3};
    74. ListNode node = ListNode.setNodes(0, nums);
    75. ListNode.printListData(sortList(node));
    76. }
    77. }

    harryptter / LeetcodeTop100 · GitCode

  • 相关阅读:
    树莓派上,docker下安装rancher与k8s,docker版本对应关系
    背包九讲(部分)
    B. Difference Array--Codeforces Round #808 (Div. 1)
    免登陆 同步脚本 zookeeper kafka集群详细安装步骤
    python入门(12)面向对象:标准库与面向对象小结
    #Linux杂记--将Python3的源码编译为.so文件方法与Linux环境下的交叉编译方法
    六、python的csv模块
    将自己的代码发布成可以pip安装的包
    在 Rust 中实现 TCP : 4. 完成握手
    Android 应用流量监控实践
  • 原文地址:https://blog.csdn.net/harryptter/article/details/133361183