🌗 86. 分隔链表

吞佛童子2022年10月10日
  • algorithm
  • list
小于 1 分钟

🌗 86. 分隔链表

难度: 🌗

问题描述

img_7.png


解法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        // 思路:
        // 保存 left ,在 left 后面继续插入 < x 的节点
        if(head == null || head.next == null) {
            return head;
        }
        ListNode left = new ListNode(-1);
        ListNode res = left;
        ListNode pre = new ListNode(-1);
        ListNode right = pre;
        pre.next = head;
        ListNode cur = head;
        while(cur != null) {
            if(cur.val < x) {
                // 在 left 后面插入
                ListNode next = cur.next;
                cur.next = null;
                pre.next = next;
                left.next = new ListNode(cur.val);
                left = left.next;                
                cur = next;
            } else {
                pre = cur;
                cur = cur.next;
            }
        }
        // 拼接 left
        left.next = right.next;
        return res.next;
    }
}

输出

img_6.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou