链表_leetcode86

#Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None

class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""

if not head or not head.next:
return head

if x < 1:
return head

cur = head
count = 1

while cur and count < x:
cur = cur.next
count += 1

if count < x :
return head

xNode = cur

cur = head
leftNode = None
rightNode = None

left = None
right = None

while cur :

if cur.val < xNode.val and leftNode == None:
leftNode =cur
left = leftNode

if cur.val >= xNode.val and rightNode == None:
rightNode = cur
right = rightNode


if cur.val < xNode.val:
left.next = cur
left = cur

else:
right.next = cur
right = cur

cur = cur.next

left.next = rightNode

return leftNode


class Solution2(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""

if head is None or head.next is None or x is None:
return head

p1 = head1 = ListNode(0)
p2 = head2 = ListNode(0)
p = head

while p:
if p.val < x:
p1.next = p
p1 = p1.next
else:
p2.next = p
p2 = p2.next
p = p.next
p1.next = head2.next
p2.next = None


return head1.next


posted @   AceKo  阅读(152)  评论(0编辑  收藏  举报
编辑推荐:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
点击右上角即可分享
微信分享提示