【leetcode】86. 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.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

解题思路:我的方法和【leetcode】328. Odd Even Linked List 一样,使用less 和 great 两个指针,分别指向小于和等于或大于的节点,最后再把less的尾节点指向great的头结点即可。

代码如下:

# 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
        """
        lessHead = less = greatHead = great = None
        current = head
        while current != None:
            tmp = current.next
            current.next = None
            if current.val < x:
                if lessHead == None:
                    lessHead = current
                    less = lessHead
                else:
                    less.next = current
                    less = less.next
            else:
                if greatHead == None:
                    greatHead = great = current
                else:
                    great.next = current
                    great = great.next
            current = tmp
        if less != None:
            less.next = greatHead
        else:
            lessHead = greatHead
        return lessHead

 

posted @ 2018-12-29 10:25  seyjs  阅读(99)  评论(0编辑  收藏  举报