Leetcode 86 分割链表

  JAVA:

        public final ListNode partition(ListNode head, int x) {
            ListNode leftHead = new ListNode(), rightHead = new ListNode(),
                    left = leftHead, right = rightHead;
            while (head != null) {
                if (head.val < x) {
                    left.next = head;
                    left = left.next;
                } else {
                    right.next = head;
                    right = right.next;
                }
                head = head.next;
            }
            right.next = null;
            left.next = rightHead.next;
            return leftHead.next;
        }

  JS:

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} x
 * @return {ListNode}
 */
var partition = function (head, x) {
    let leftHead = new ListNode(), rightHead = new ListNode(),
        left = leftHead, right = rightHead;
    while (head != null) {
        if (head.val < x) {
            left.next = head;
            left = left.next;
        } else {
            right.next = head;
            right = right.next;
        }
        head = head.next;
    }
    right.next = null;
    left.next = rightHead.next;
    return leftHead.next;
};

posted @ 2021-06-26 21:39  牛有肉  阅读(40)  评论(0编辑  收藏  举报