86. Partition List
# Runtime: 36 ms, faster than 62.35%; Memory Usage: 14 MB, less than 100.00%
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
ahead = ListNode() # 建立原链表的哨兵节点,用于删除比x小的节点
bhead = ListNode() # 建立新链表的哨兵节点,该链表存储比x小的节点
ahead.next = head
apre, bpre = ahead, bhead
while head:
if head.val < x: # 在原链表中删除该节点,并在新链表中添加该节点
apre.next = head.next
bpre.next = ListNode(head.val)
bpre = bpre.next
head = head.next
else:
apre = apre.next
head = head.next
bpre.next = ahead.next # 让删除小于x节点的原链表接在新链表之后
return bhead.next