链表_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


猜你喜欢

转载自www.cnblogs.com/lux-ace/p/10557184.html
今日推荐