Leetcode 86:分隔链表(最详细解决方案!!!)

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

解题思路

这个问题和这篇文章Leetcode 328:奇偶链表(最详细解决方案!!!)中的问题很类似。我们这里同样使用双链表解决,只是这里的双链表一个是包含<x的元素,一个是包含>=x的元素。

h1 -> 1 -> 2 -> 2
h2 -> 4 -> 3 -> 5

我们这里有两种解法,第一种通过建立两个链表实现。

class Solution:
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head

        cur = head
        pre_min = cur_min = ListNode(-1)
        pre_max = cur_max = ListNode(-1)

        while cur != None:
            if cur.val < x:
                cur_min.next = cur
                cur_min = cur_min.next
            else:
                cur_max.next = cur
                cur_max = cur_max.next

            cur = cur.next

        cur_min.next = pre_max.next
        cur_max.next = None
        return pre_min.next

第二种则是通过链表中的指针操作

class Solution:
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head

        pre_min, pre_max, cur_min, cur_max = None, None, None, None
        cur = head

        while cur != None:
            if cur.val < x and pre_min == None:
                pre_min = cur_min = cur
            elif cur.val >= x and pre_max == None:
                pre_max = cur_max = cur
            elif cur.val < x and pre_min != None:
                cur_min.next = cur
                cur_min = cur_min.next
            elif cur.val >= x and pre_max != None:
                cur_max.next = cur
                cur_max = cur_max.next

            cur = cur.next

        if cur_min != None:
            cur_min.next = pre_max

        if cur_max != None:
            cur_max.next = None

        if pre_min != None:
            return pre_min
        return pre_max

我这里更倾向于第一种写法,应该思路更加清晰。

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

猜你喜欢

转载自blog.csdn.net/qq_17550379/article/details/80661781