思路:
1、遍历原链表,分别找到小于x的节点与大于等于x的节点组成的两个链表small和big;
2、拼接small和big,small在前。
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
if not head:
return head
# 小于x的节点,ans.next是返回值
small = ans = ListNode(-1)
# 不小于x的节点
big = head_big = ListNode(-1)
# 遍历指针
cur = head
while cur:
if cur.val < x:
small.next = cur
small = small.next
else:
big.next = cur
big = big.next
cur = cur.next
# 将两个链表段拼接,小于x的在前,不小于x的在后
big.next = None
small.next = head_big.next
return ans.next