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;
            }
        }
    
    }
  • 相关阅读:
    2018杭州初雪
    李宗盛
    张爱玲(句子迷)
    RFBnet论文笔记
    AXI总线简介、ID分析、DMA、Vivado烧录、系统集成
    axi总线之零:概述
    怎么理解 Redis 事务?
    Redis 集群最大节点个数是多少?
    怎么测试 Redis 的连通性?
    Redis 集群如何选择数据库?
  • 原文地址:https://www.cnblogs.com/null00/p/5097715.html
Copyright © 2011-2022 走看看