1. 题目
2. 分析
这题没有太大难度,主要是熟悉代码。
3. 代码
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]:
lower_head = None
lower_head_bak = None
upper_head = None
upper_head_bak = None
if head is None:
return None
while(head):
tmp = head.next
if head.val < x:
if lower_head:
lower_head.next = head
else:
lower_head_bak = head
lower_head = head # 更新结果
lower_head.next = None
else:
if upper_head is None:
upper_head_bak = head
else:
upper_head.next = head
upper_head = head
upper_head.next = None
head = tmp
if lower_head :
lower_head.next = upper_head_bak
return lower_head_bak
elif lower_head is None and upper_head_bak:
return upper_head_bak