美文网首页
86. Partition List

86. Partition List

作者: exialym | 来源:发表于2016-11-18 11:15 被阅读8次

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
根据给出的链表和基准值,把链表分为两部分,比基准值小的在前,大的在后,两部分中的元素分别保持原来在链表中的顺序。
很直接的实现就好,构造出左右两个链表,然后拼起来:

var partition = function(head, x) {
    var leftHead = null;
    var left = null;
    var rightHead = null;
    var right = null;
    var next = null;
    while (head) {
        next = head.next;
        if (head.val<x) {
            if (leftHead) left.next = head;
            else leftHead = head;
            left = head;
            head.next = null;
        } else {
            if (rightHead) right.next = head;
            else  rightHead = head;
            right = head;
            head.next = null;
        }
        head = next;
    }
    if (left) {
        left.next = rightHead;
        return leftHead;
    } else {
        return rightHead;
    }
};

相关文章

网友评论

      本文标题:86. Partition List

      本文链接:https://www.haomeiwen.com/subject/dtwjpttx.html