Skip to content

Commit

Permalink
Merge Two Sorted Lists
Browse files Browse the repository at this point in the history
  • Loading branch information
TonyKim9401 committed Sep 29, 2024
1 parent ec10a0d commit ddabf0b
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions merge-two-sorted-lists/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// TC: O(n)
// n = length sum of list1 and list2
// SC: O(n)
// n = node 0 ~ length sum of list1 and list2
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode node = new ListNode(0);
ListNode output = node;

while (list1 != null && list2 != null) {
if (list1.val > list2.val) {
node.next = list2;
list2 = list2.next;
} else {
node.next = list1;
list1 = list1.next;
}
node = node.next;
}

if (list1 == null) node.next = list2;
if (list2 == null) node.next = list1;

return output.next;
}
}

0 comments on commit ddabf0b

Please sign in to comment.