参考知识:
题目:
题目来源:力扣
代码:
from typing import Optional
class ListNode:
''' 链表结点的数据结构 '''
def __init__(self,val=0,next=None):
self.val=val
self.next=next
def creatLink(lst:list[int])->Optional[ListNode]:
''' 将list转换为链表 '''
if not lst:return None
head=ListNode(0)
j=head
for item in lst:
node = ListNode(item)
j.next=node
j=node
return head.next
def node_list(head:Optional[ListNode])->list[int]:
''' 将链表转换为list '''
res=[]
while head :
res.append(head.val)
head=head.next
print(res)
return res
class Solution:
def partition(self,head:Optional[ListNode],x:int)->Optional[ListNode]:
small,large=ListNode(0),ListNode(0)
i,j=small,large
while head:
if head.val<x:
i.next=head
i=head
else:
j.next=head
j=head
head=head.next
i.next=large.next # 连接small、large2个链表
j.next=None # 尾节点指向None
return small.next
def run(self,lst,x):
head = self.partition(creatLink(lst),x=x)
res = node_list(head)
return res
if __name__ == '__main__':
s=Solution()
s.run(lst=[1,4,3,2,5,2],x=3)