1. 程式人生 > 其它 >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; };