• 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;
            }
        }
    
    }
  • 相关阅读:
    机器学习介绍
    Day03 作业
    Python函数基础
    Python练习
    耳机 线控 控制播放
    edittext 底线颜色
    从service启动activity startActivity慢 的解决方案
    国产手机没有google services 和google play崩溃,判断google services是否存在
    检测耳机插入和拔出
    获取view宽高
  • 原文地址:https://www.cnblogs.com/null00/p/5097715.html
Copyright © 2020-2023  润新知