zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

    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.

    思路:

    分成两个链表,然后链接

    package list;
    
    public class PartitionList {
    
        public ListNode partition(ListNode head, int x) {
            ListNode leftNode = new ListNode(0);
            ListNode rightNode = new ListNode(0);
            ListNode p = leftNode;
            ListNode q = rightNode;
            while (head != null) {
                if (head.val < x) {
                    leftNode.next = head;
                    leftNode = leftNode.next;
                } else {
                    rightNode.next = head;
                    rightNode = rightNode.next;
                }
                head = head.next;
            }
            rightNode.next = null;
            leftNode.next = q.next;
            return p.next;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ListNode a1 = new ListNode(1);
            ListNode a2 = new ListNode(4);
            ListNode a3 = new ListNode(3);
            ListNode a4 = new ListNode(2);
            ListNode a5 = new ListNode(5);
            ListNode a6 = new ListNode(2);
            a1.next = a2;
            a2.next = a3;
            a3.next = a4;
            a4.next = a5;
            a5.next = a6;
            a6.next = null;
            PartitionList p = new PartitionList();
            ListNode head = p.partition(a1, 3);
            while (head != null) {
                System.out.println(head.val);
                head = head.next;
            }
        }
    
    }
  • 相关阅读:
    信息收集与扫描
    流密码
    信息安全面临的威胁
    .net core Web应用启动类
    .net core 1.0 Web MVC 自定义认证过程
    彻底脱离循环与结束当下循环
    Java多线程:Thread中的实例方法
    memcached安装问题
    五月的仓颉
    json时间格式化方法
  • 原文地址:https://www.cnblogs.com/null00/p/5097715.html
Copyright © 2011-2022 走看看