partition List Leetcode Python

本文介绍了一种链表分区算法,该算法将链表中的节点按指定值x进行划分,使得所有小于x的节点位于大于等于x的节点之前,并保持原有相对顺序不变。算法的时间复杂度为O(n),通过一次遍历即可完成分区。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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.



算法复杂度O(n)

遍历一遍链表依次把小于X的值加到第一个链表后,大于等于X的加到第二个链表后。遍历完毕后再把第一个链表的尾巴指向第二链表的头。

返回第一个链表的头。

The time complexity is O(n), we need to go through the whole linklist and compare the tmp value with x. If the tmp value is smaller than X, we append it to the first linklist otherwise the second. Then append the head of the second linklist to the tail of the first linklist. Return the head of the first linklist.

I was also thing about just swap positions in the linklist but have no idea right now. If anyone have it please do not hesitate to leave me some message.

Below is the code:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @param x, an integer
    # @return a ListNode
    def partition(self, head, x):
        dummy=ListNode(0)
        dummy.next=head
        dummy1=ListNode(0)
        dummy2=ListNode(0)
        head1=dummy1
        head2=dummy2
        tmp=head
        while tmp:
            if tmp.val<x:
                head1.next=tmp
                tmp=tmp.next
                head1=head1.next
                head1.next=None
            else:
                head2.next=tmp
                tmp=tmp.next
                head2=head2.next
                head2.next=None
        head1.next=dummy2.next
        head=dummy1.next
        return head


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值