1. 题目
2. 分析
这题没有太大难度,主要是熟悉代码。
3. 代码
# 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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.