Skip to content

Commit 90628c0

Browse files
committed
optimize merge-two-sorted-lists
1 parent 31ba2f4 commit 90628c0

1 file changed

Lines changed: 13 additions & 23 deletions

File tree

merge-two-sorted-lists/parkhojeong.py

Lines changed: 13 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,21 @@
55
# self.next = next
66
class Solution:
77
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
8-
if not list1:
9-
return list2
10-
if not list2:
11-
return list1
12-
13-
14-
if list1.val > list2.val:
15-
list1, list2 = list2, list1
16-
17-
head = list1
8+
dummy_head = ListNode()
9+
cur = dummy_head
1810

1911
while list1 and list2:
20-
if not list1.next:
21-
list1.next = list2
22-
break
23-
24-
25-
if list2.val <= list1.next.val:
26-
list2_next = list2.next
27-
28-
list2.next = list1.next
29-
list1.next = list2
30-
list2 = list2_next
31-
else:
12+
if list1.val <= list2.val:
13+
cur.next = list1
3214
list1 = list1.next
15+
else:
16+
cur.next = list2
17+
list2 = list2.next
18+
cur = cur.next
3319

20+
if list1:
21+
cur.next = list1
22+
elif list2:
23+
cur.next = list2
3424

35-
return head
25+
return dummy_head.next

0 commit comments

Comments
 (0)