Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added python code reorder list #28

Merged
merged 1 commit into from
Dec 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions docs/linked-list/reorder-list.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ defaultValue="java"
values={[
{ label: 'Java', value: 'java', },
{ label: 'C++', value: 'cpp', },
{ label: 'Python', value: 'python', },
]
}>
<TabItem value="java">
Expand Down Expand Up @@ -122,5 +123,50 @@ public:
};
```

</TabItem>
<TabItem value="python">

```python
# Reorder List
# 时间复杂度O(n),空间复杂度O(1)
class Solution:
def reorderList(self, head):
if head is None or head.next is None: return

slow, fast = head, head
prev = None
while fast and fast.next:
prev = slow
slow = slow.next
fast = fast.next.next
prev.next = None # cut at middle

slow = self.reverse(slow)

# merge two lists
curr = head
while curr.next:
tmp = curr.next
curr.next = slow
slow = slow.next
curr.next.next = tmp
curr = tmp
curr.next = slow

def reverse(self, head):
if head is None or head.next is None: return head

prev = head
curr = head.next
next = curr.next
while curr:
curr.next = prev
prev = curr
curr = next
next = next.next if next else None
head.next = None
return prev
```

</TabItem>
</Tabs>