1.双指针法
1.双指针法 before链表用来存放比x小的节点,after节点用来存放比x大的节点。注意要设置头节点,因为这样可以减少判断条件
/*
* @lc app=leetcode.cn id=86 lang=javascript
*
* [86] 分隔链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} x
* @return {ListNode}
*/
var partition = function (head, x) {
let beforeHead = (before = new ListNode())
let afterHead = (after = new ListNode())
while (head) {
if (head.val < x) {
before.next = head
before = before.next
} else {
after.next = head
after = after.next
}
head = head.next
}
after.next = null
before.next = afterHead.next
return beforeHead.next
}
// @lc code=end