Solution 1Dummy Node
- TimeO(n + m)
- SpaceO(1)
where, n and m are the number of nodes in list1 and list2 respectively.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
'''
Time Complexity: O(n + m)
Space Complexity: O(1)
where, n and m are the number of nodes in list1 and list2 respectively.
'''
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode()
node = dummy
while list1 and list2:
if list1.val < list2.val:
temp = list1.next
list1.next = None
node.next = list1
node = list1
list1 = temp
else:
temp = list2.next
list2.next = None
node.next = list2
node = list2
list2 = temp
node.next = list1 if list1 else list2
return dummy.next/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode();
ListNode cur = dummy;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
cur.next = list1;
list1 = list1.next;
} else {
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
if (list1 != null) {
cur.next = list1;
} else {
cur.next = list2;
}
return dummy.next;
}