R3-双指针(快慢指针)
新建两个链表
一个链表记录<x的值
一个链表记录>=x的值
拼接即可
# 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]:
#新建链表以及指针表示
low_dummy,high_dummy=ListNode(0),ListNode(0)
low,high=low_dummy,high_dummy
while head:
if head.val<x:
low.next=head
low=low.next
else:
high.next=head
high=high.next
head=head.next
#拼接
low.next=high_dummy.next
high.next=None
return low_dummy.next
ps:
#新建链表以及指针表示
low_dummy,high_dummy=ListNode(0),ListNode(0)
low,high=low_dummy,high_dummy