Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

python3 solution to #21#168

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
selenaxiao wants to merge1 commit intofishercoder1534:master
base:master
Choose a base branch
Loading
fromselenaxiao:21_solution
Open
Changes fromall 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
30 changes: 30 additions & 0 deletionspython3/21.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@

# https://leetcode.com/problems/merge-two-sorted-lists/
# Iterative solution
class Solution:
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
tempHead = ListNode() # Empty node to be head of merged list
temp = tempHead # End node of merged list, append new nodes to end of temp

# While BOTH l1 and l2 still have nodes
while (l1 is not None and l2 is not None):
# If current node of l1 has a smaller value than current node of l2
if (l1.val < l2.val):
# Append l1 node to merged list
temp.next = l1
# Go to next l1 node
l1 = l1.next
else:
temp.next = l2
l2 = l2.next

# Go to new end of merged list
temp = temp.next

# Either l1, l2, or neither have nodes left
# Can directly append all of the remaining nodes to merged list
temp.next = l1 if l1 is not None else l2

# tempHead is empty node, return the actual head node of merged list
return tempHead.next


[8]ページ先頭

©2009-2025 Movatter.jp