• 【数据结构与算法】链表的分割


    需求分析:

            将链表分为两个部分在X前是小于X的,在X后是大于X的。只需要分割不需要排序。

    实现思路:

            通过从头节点开始遍历,判断小于X的放入一条链表种,大于X的放入另一个链表中,最后将两条链表相连,X置于两条链表相连的中点,如果链表中没有X则添加一个X节点。

    实现方法:

    1. /**
    2. * 链表的分割
    3. * @param node 传入头节点
    4. * @param x 分割数
    5. * @return
    6. */
    7. public static Node partition(Node node, int x) {
    8. Node linked1 = new Node(0);
    9. Node linked2 = new Node(0);
    10. Node curr1 = linked1;
    11. Node curr2 = linked2;
    12. Node head = node;
    13. Node nodeX = null;
    14. while (head != null) {
    15. if (head.val < x) {
    16. curr1.next = head;
    17. curr1 = curr1.next;
    18. } else if (head.val > x) {
    19. curr2.next = head;
    20. curr2 = curr2.next;
    21. } else {
    22. nodeX = head;
    23. }
    24. head = head.next;
    25. }if (nodeX==null){
    26. nodeX=new Node(4);
    27. }
    28. curr1.next = nodeX;
    29. nodeX.next = linked2.next;
    30. curr2.next = null;
    31. return linked1.next;
    32. }
    33. //链表的节点类
    34. public static class Node {
    35. private int val;
    36. private Node next;
    37. public Node(int val) {
    38. this.val = val;
    39. }
    40. }

    测试:

    1. public static void main(String[] args) {
    2. Node node1 = new Node(1);
    3. Node node2 = new Node(3);
    4. Node node3 = new Node(5);
    5. Node node4 = new Node(7);
    6. Node node5 = new Node(6);
    7. Node node6 = new Node(4);
    8. Node node7 = new Node(2);
    9. node1.next = node2;
    10. node2.next = node3;
    11. node3.next = node4;
    12. node4.next = node5;
    13. node5.next = node6;
    14. node6.next = node7;
    15. System.out.print("分割前:");
    16. Node head1 =node1;
    17. while (head1 != null) {
    18. System.out.print(head1.val);
    19. head1 = head1.next;
    20. }
    21. System.out.println();
    22. System.out.print("分割后:");
    23. Node head2 = partition(node1, 4);
    24. while (head2 != null) {
    25. System.out.print(head2.val);
    26. head2 = head2.next;
    27. }
    28. }

    测试结果:

  • 相关阅读:
    IPv6改造方案:协议转换技术
    python is not set from command line or npm configuration
    springboot+vue+小程序电影购票系统源码
    低代码如何增强团队应用开发能力?
    使用信号量解决并发问题
    Python实现XMind测试用例快速转Excel用例
    【poi导出excel模板——通过建造者模式+策略模式+函数式接口实现】
    Maven下载、安装、配置教程
    R语言在生态环境领域中的实践技术应用
    天龙八部门派采集任务坐标
  • 原文地址:https://blog.csdn.net/c1390527393/article/details/133810840