Skip to content

Commit 8710f88

Browse files
committed
Leetcode Accepted.
1 parent e108b8d commit 8710f88

2 files changed

Lines changed: 40 additions & 1 deletion

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Merge Two Sorted Lists
2+
# https://leetcode.com/problems/merge-two-sorted-lists/
3+
4+
# Definition for singly-linked list.
5+
# class ListNode(object):
6+
# def __init__(self, val=0, next=None):
7+
# self.val = val
8+
# self.next = next
9+
class Solution(object):
10+
def mergeTwoLists(self, l1, l2):
11+
# create an empty head for the list
12+
head = ListNode()
13+
# assign pointer to this head, this is to keep track.
14+
ptr = head
15+
# while both the lists are still alive.
16+
while(l1 and l2):
17+
if (l1.val < l2.val):
18+
ptr.next = l1
19+
l1 = l1.next
20+
else:
21+
ptr.next = l2
22+
l2 = l2.next
23+
ptr = ptr.next
24+
# add remaining of the lists
25+
if (l1):
26+
ptr.next = l1
27+
if (l2):
28+
ptr.next = l2
29+
# return the head next since head is empty pointer.
30+
return head.next
31+
"""
32+
:type l1: ListNode
33+
:type l2: ListNode
34+
:rtype: ListNode
35+
"""
36+

Blind 75/README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,10 @@
172172
You can also solve this porblem by having a hash table and making note of all the nodes seen so far.
173173
</p>
174174
</li>
175-
<li>Merge Two Sorted Lists</li>
175+
<li><a href="Programs/Merge Two Sorted Lists.py">Merge Two Sorted Lists</a>
176+
<p><b>Approach</b>: Simple O(n) merging, by traversing both lists at the same time.
177+
</p>
178+
</li>
176179
<li>Merge K Sorted Lists</li>
177180
<li>Remove Nth Node From End Of List</li>
178181
<li>Reorder List</li>

0 commit comments

Comments
 (0)