python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
# 创建两个虚拟头节点
smaller_head = ListNode(0)
greater_head = ListNode(0)
# 初始化两个指针
smaller = smaller_head
greater = greater_head
# 遍历链表
while head:
if head.val < x:
# 将节点加入到小于 x 的链表中
smaller.next = head
smaller = smaller.next
else:
# 将节点加入到大于等于 x 的链表中
greater.next = head
greater = greater.next
head = head.next
# 断开大于等于 x 链表的末尾
greater.next = None
# 连接两个链表
smaller.next = greater_head.next
return smaller_head.next