From bd2eaa54007d51c433d1237e4303c36c361c9e2f Mon Sep 17 00:00:00 2001 From: lantin2016 Date: Wed, 4 Dec 2024 16:27:10 +0800 Subject: [PATCH] added python code partition list (#21) Co-authored-by: lantin2016 --- docs/linked-list/partition-list.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/docs/linked-list/partition-list.md b/docs/linked-list/partition-list.md index 5dcee7b65..eb4a7dcea 100644 --- a/docs/linked-list/partition-list.md +++ b/docs/linked-list/partition-list.md @@ -25,6 +25,7 @@ defaultValue="java" values={[ { label: 'Java', value: 'java', }, { label: 'C++', value: 'cpp', }, +{ label: 'Python', value: 'python', }, ] }> @@ -91,5 +92,34 @@ public: }; ``` + + + +```python +# Partition List +# 时间复杂度O(n),空间复杂度O(1) +class Solution: + def partition(self, head, x): + left_dummy = ListNode(-1) # 头结点 + right_dummy = ListNode(-1) # 头结点 + + left_cur = left_dummy + right_cur = right_dummy + cur = head + while cur is not None: + if cur.val < x: + left_cur.next = cur + left_cur = cur + else: + right_cur.next = cur + right_cur = cur + cur = cur.next + + left_cur.next = right_dummy.next + right_cur.next = None + + return left_dummy.next +``` +