leetcode 86. 分隔链表

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 1 public class _86 {
 2     public ListNode partition(ListNode head, int x) {
 3         if (head == null || head.next == null) return head;
 4 
 5         ListNode left = new ListNode(0);
 6         ListNode right = new ListNode(0);
 7         ListNode p = head;
 8         ListNode lp = left, rp = right;
 9         while (p != null){
10             if (p.val < x) {
11                 lp.next = p;
12                 lp = lp.next;
13             } else {
14                 rp.next = p;
15                 rp = rp.next;
16             }
17             p = p.next;
18         }
19 
20         lp.next = right.next;
21         rp.next = null;
22 
23         return left.next;
24     }
25 
26     public static void main(String[] args) {
27         int[] elems = {1,4,3,2,5,2};
28         ListNode head = _82.create(elems);
29         ListNode p = new _86().partition(head, 1);
30 
31         while (p != null){
32             System.out.print(p.val+", ");
33             p = p.next;
34         }
35     }
36 }
原文地址:https://www.cnblogs.com/yfs123456/p/11552762.html