参考知识:
- 什么是链表
- Optional有什么用
题目:
题目来源:力扣
代码:
from typing import Optionalclass ListNode:''' 链表结点的数据类型 '''def __init__(self, val=0,next=None):self.val = valself.next = nextdef convert_to_linked_list(lst):''' 将list转换为单链表 '''if not lst:return Nonehead = ListNode(lst[0]) # list第一个元素作为head结点i = headfor i in range(1, len(lst)):new_node = ListNode(lst[i]) # 元素结点化i.next = new_node # 追加新nodei = i.next # 结点标志位移到下一结点return head #返回head结点class Solution:''' 小于x的元素在x左边,大于x的元素在x右边,保持相对位置不变 '''def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:small, large = ListNode(0), ListNode(0) #声明2个链表i, j = small, large # 两个链表的结点标志位while head:if head.val < x: # <x 的放在small链表i.next = headi = i.nextelse: # >=x 的放在large链表j.next = headj = j.nexthead = head.next # 比较完当前head后,比较下一个i.next = large.next # 连接2个链表,i结点 即 large链表的第二个结点j.next = None # 尾结点指向Nonereturn small.nextdef run(self,lst,x):''' 以list形式输出最终结果 '''res=[]head = self.partition(head=convert_to_linked_list(lst),x=x)while head:res.append(head.val)head=head.nextreturn resif __name__ == '__main__':lst=[1,4,3,2,5,2]s=Solution()print(s.run(lst,x=3))