zoukankan      html  css  js  c++  java
  • 链表_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


  • 相关阅读:
    练习2-15 求简单交错序列前N项和(15 分)
    js预解析实例
    one:arguments对象伪数组
    第一章 评估工具
    第6章条件处理
    第五章----过程
    第4章 数据传递.寻址和算术运算
    第3章 汇编语言基础
    第2章-------------IA-32处理器体系结构
    第一章-------基本概念
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10557184.html
Copyright © 2011-2022 走看看