LeetCode 86. Partition List 20170612

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

题目大意:给定一个list和1个值值,把list分为两部分,小于x的放在前,大于等于x的放在后,两部分各自保持原有顺序

解题思路:用头结点的方法能够较好的解决这道题。创建两个头结点head1和head2,head1是小于x值的节点的链表,head2大于等于x值的节点的链表。遍历整个链表,把小于x的节点加到head1链表,把大于等于x的节点加到head2链表。

class Solution(object):
  def partition(self, head, x):
    """
    :type head: ListNode
    :type x: int
    :rtype: ListNode
    """
    head1 = ListNode(0)
    head2 = ListNode(0)
    p = head
    p1 = head1
    p2 = head2
    if head == None:
      return head
    if head.next == None:
      return head
    while p != None:
      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

原文地址:https://www.cnblogs.com/fangdai/p/6993371.html