Leetcode 86 分割連結串列
阿新 • • 發佈:2021-06-26
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; returnleftHead.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; };