[Leetcode]@python 86. Partition List.py

题目链接

https://leetcode.com/problems/partition-list/

题目原文

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.

题目大意

给定一个值,将链表分成两个部分,前面的部分比这个值小,后面的值大于或者等于这个值。

解题思路

创建两个头结点head1和head2,head1这条链表是小于x值的节点的链表,head2链表是大于等于x值的节点的链表,然后将head2链表链接到head链表的尾部即可

代码

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
        """
        head1 = ListNode(0)
        head2 = ListNode(0)
        tmp = head
        phead1 = head1
        phead2 = head2
        while tmp:
            if tmp.val < x:
                phead1.next = tmp
                tmp = tmp.next
                phead1 = phead1.next
                phead1.next = None
            else:
                phead2.next = tmp
                tmp = tmp.next
                phead2 = phead2.next
                phead2.next = None
        phead1.next = head2.next
        head = head1.next
        return head
原文地址:https://www.cnblogs.com/slurm/p/5206185.html