From d37bfa23e957546744b811633cec7975b71df50e Mon Sep 17 00:00:00 2001 From: huangge1199 Date: Tue, 9 Feb 2021 12:34:33 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=9B=E6=89=A3=EF=BC=9A86.=20=E5=88=86?= =?UTF-8?q?=E9=9A=94=E9=93=BE=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../code/leet/study/t20210209/Partition.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 LeetCode/src/main/java/com/code/leet/study/t20210209/Partition.java diff --git a/LeetCode/src/main/java/com/code/leet/study/t20210209/Partition.java b/LeetCode/src/main/java/com/code/leet/study/t20210209/Partition.java new file mode 100644 index 0000000..adf7db5 --- /dev/null +++ b/LeetCode/src/main/java/com/code/leet/study/t20210209/Partition.java @@ -0,0 +1,33 @@ +package com.code.leet.study.t20210209; + +import com.code.leet.entiy.ListNode; + +/** + * 给你一个链表和一个特定值 x ,请你对链表进行分隔,使得所有小于 x 的节点都出现在大于或等于 x 的节点之前。 + *

+ * 你应当保留两个分区中每个节点的初始相对位置。 + */ +public class Partition { + /** + * 86. 分隔链表 + */ + public ListNode partition(ListNode head, int x) { + ListNode max = new ListNode(0); + ListNode min = new ListNode(0); + ListNode maxHead = max; + ListNode minHead = min; + while (head != null) { + if (head.val >= x) { + maxHead.next = head; + maxHead = maxHead.next; + } else { + minHead.next = head; + minHead = minHead.next; + } + head = head.next; + } + maxHead.next = null; + minHead.next = max.next; + return min.next; + } +}