From 14d5cc2e853f46cf4aa1d4c4a5e9d193d32a824a Mon Sep 17 00:00:00 2001 From: Selena Xiao <55109903+selenaxiao@users.noreply.github.com> Date: Mon, 9 May 2022 17:58:21 -0400 Subject: [PATCH] python3 solution to #21 --- python3/21.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 python3/21.py diff --git a/python3/21.py b/python3/21.py new file mode 100644 index 0000000000..62cd3a807a --- /dev/null +++ b/python3/21.py @@ -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 + pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy