Ray-56 / like-algorithms

每天一道算法题,突破自己
2 stars 1 forks source link

✅86. 分隔链表 #137

Open Ray-56 opened 4 years ago

Ray-56 commented 4 years ago

86. 分隔链表

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

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

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
Ray-56 commented 4 years ago

双指针解

var partition = function(head, x) {
    let beforeHead = new ListNode();
    let afterHead = new ListNode();
    let before = beforeHead;
    let after = afterHead;

    let cur = head;
    while (cur) {
        if (cur.val < x) {
            before.next = cur;
            before = before.next;
        } else {
            after.next = cur;
            after = after.next;
        }

        cur = cur.next;
    }
    after.next = null;

    before.next = afterHead.next;
    return beforeHead.next;
};