![![在这里插入图片描述](https://img-在这里插入图片描述
blog.csdnimg.cn/6b961d2814414fa1924f6b2f040cd339.png)](https://i-blog.csdnimg.cn/blog_migrate/7fc2735585658046a82c14335c768151.png)
解题思路
- 找到第一个大于等于x的节点staticNode,之后所有小于x的非法节点都会插入该节点之前
- 判断staticNode之前是否存在小于x的合法节点。有则将最靠近staticNode的节点设置为vaildNode。没有则为null
- 双指针遍历链表,从vaildNode开始遍历。找出非法节点,插入validNode之后。同时validNode = validNode.next;
function partition(head: ListNode | null, x: number): ListNode | null {
if(!head) return null;
let res = head;
let staticNode = head;
while (staticNode && staticNode.val < x) {
staticNode = staticNode.next;
}
if(!staticNode) return head;
let validNode = head.val < staticNode.val ? head : null;
if (validNode !== null) {
res = validNode;
while (validNode.next && validNode.next.val < staticNode.val) {
validNode = validNode.next;
if (validNode.next.val >= staticNode.val) {
break;
}
}
}
let current = head,
pre = head.next;
main: while (true) {
if (validNode) {
current = validNode;
pre = validNode.next;
}
if(!pre) break;
while (pre.val >= x) {
pre = pre.next;
current = current.next;
if (!pre) {
break main;
}
if (pre.val < x) {
break;
}
}
if (validNode) {
current.next = pre.next;
pre.next = validNode.next;
validNode.next = pre;
validNode = validNode.next
} else {
current.next = pre.next;
pre.next = staticNode;
res = pre;
validNode = pre;
}
}
return res;
};