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

Commit 07a6efa

Browse files
Added solution for the Merge Two Sorted Lists problem
Signed-off-by: Krishna Kishore Shetty <kkshetty.work@pm.me>
1 parent ad533f5 commit 07a6efa

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

‎merge_two_sorted_lists/Solution.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
8+
# Create a dummy node for our result list
9+
resultList = ListNode()
10+
11+
# Like a pointer to the last node on the list, which we can use to add more elemets to the list.
12+
resultListCurrent = resultList
13+
14+
# Handle cases of one or both lists being empty
15+
if list1 is None and list2 is None:
16+
return None
17+
18+
if list1 is None and list2 is not None:
19+
return list2
20+
21+
if list2 is None and list1 is not None:
22+
return list1
23+
24+
while (list1 is not None) and (list2 is not None):
25+
if list1.val <= list2.val:
26+
resultListCurrent.next = list1
27+
list1 = list1.next
28+
else:
29+
resultListCurrent.next = list2
30+
list2 = list2.next
31+
32+
resultListCurrent = resultListCurrent.next
33+
34+
# One of the two list pointers will be None.
35+
# Add the remaining elements of the non-empty list to the result list
36+
if list1 is not None:
37+
while list1 is not None:
38+
resultListCurrent.next = list1
39+
list1 = list1.next
40+
resultListCurrent = resultListCurrent.next
41+
elif list2 is not None:
42+
while list2 is not None:
43+
resultListCurrent.next = list2
44+
list2 = list2.next
45+
resultListCurrent = resultListCurrent.next
46+
47+
# Return result list without dummy node
48+
return resultList.next

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /