0
点赞
收藏
分享

微信扫一扫

分隔链表

彪悍的鼹鼠 2021-09-21 阅读 60
今日算法
题目描述:

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

说明:

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

示例 1:
示例 2:
思路:
实现:
class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode small = new ListNode();
        ListNode smallHead = small;
        ListNode big = new ListNode();
        ListNode bigHead = big;
        ListNode cur = head;
        while (cur != null) {
            if (cur.val < x) {
                small.next = cur;
                small = small.next;
            } else {
                big.next = cur;
                big = big.next;
            }
            cur = cur.next;
        }
        big.next = null;
        small.next = bigHead.next;
        return smallHead.next;
    }
}
举报

相关推荐

0 条评论