• Partition List


    描述
    Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater
    than or equal to x.
    You should preserve the original relative order of the nodes in each of the two partitions.
    For example, Given 1->4->3->2->5->2

    and x = 3, return 1->2->2->4->3->5

    分析

    这道题就是说给定一个x的值,小于x都放在大于等于x的前面,并且不改变链表之间node原始的相对位置。每次看这道题我老是绕晕,纠结为什么4在3的前面。。其实还是得理解题意,4->3->5都是大于等3的数,而且这保持了他们原来的相对位置 。

    所以,这道题是不需要任何排序操作的,题解方法很巧妙。

    new两个新链表,一个用来创建所有大于等于x的链表,一个用来创建所有小于x的链表。

    遍历整个链表时,当当前node的val小于x时,接在小链表上,反之,接在大链表上。这样就保证了相对顺序没有改变,而仅仅对链表做了与x的比较判断。

    最后,把小链表接在大链表上,别忘了把大链表的结尾赋成null。

     代码:

     1 public class PartitionList {
     2 
     3     public static void main(String[] args) {
     4         // TODO Auto-generated method stub
     5         ListNode head = new ListNode(1);
     6         // head.add(1);
     7         head.add(4);
     8         head.add(3);
     9         head.add(2);
    10         head.add(5);
    11         head.add(2);
    12         head.print();
    13         System.out.println();
    14         partitionList(head, 3).print();
    15     }
    16 
    17     public static ListNode partitionList(ListNode head, int x) {
    18         if (head == null || head.next == null)
    19             return head;
    20         ListNode small = new ListNode(-1);
    21         ListNode newsmallhead = small;
    22         ListNode big = new ListNode(-1);
    23         ListNode newbighead = big;
    24         while (head != null) {
    25             if (head.data < x) {
    26                 small.next = head;
    27                 small = small.next;
    28             } else {
    29                 big.next = head;
    30                 big = big.next;
    31             }
    32             head = head.next;
    33         }
    34         big.next = null;
    35         small.next = newbighead.next;
    36         return newsmallhead.next;
    37     }
    38 }
  • 相关阅读:
    C#基元类型、引用类型和值类型
    UML类图中泛化、实现、依赖、关联、聚合、组合关系
    简述:聚集索引和非聚集索引的区别
    面向对象编程的三特性、七原则和六视点
    设计模式学习笔记——解释器模式(Interpreter)
    设计模式学习笔记——组合模式(Composite)
    程序员编程利器:20款最好的免费的IDEs和编辑器
    奇技淫巧之浏览器秒秒钟变编辑器
    前端技术Jquery与Ajax使用总结
    Chrome也疯狂之Vimium插件
  • 原文地址:https://www.cnblogs.com/ncznx/p/9321053.html
Copyright © 2020-2023  润新知