File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+
Original file line number Diff line number Diff line change 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>
You can’t perform that action at this time.
0 commit comments