力扣:86. 分隔链表(Python3)

题目:

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

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

来源:力扣(LeetCode)
链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

示例:

示例 1:

力扣:86. 分隔链表(Python3)_第1张图片

输入:head = [1,4,3,2,5,2], x = 3
输出:[1,2,2,4,3,5]


示例 2:

输入:head = [2,1], x = 2
输出:[1,2]

解法:

转成列表处理。设index为0,表示分界点,遍历列表,如果当前值(num)小于x,insert(index, num),index += 1,否则,append(num)。

代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        list1 = []
        list2 = []
        while head:
            list1.append(head.val)
            head = head.next
        index = 0
        for num in list1:
            if num < x:
                list2.insert(index, num)
                index += 1
            else:
                list2.append(num)
        head = point = ListNode()
        for num in list2:
            point.next = ListNode(num)
            point = point.next
        return head.next

你可能感兴趣的:(LeetCode,leetcode,算法,python)