Leetcode 86 分割链表

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;
};

Leetcode 86 分割链表

上一篇:牛客练习赛86


下一篇:SCUT - 86 - 加农! = 数学常识 + 栈