diff --git a/algorithms/java/src/mergedList/mergeSortedList.java b/algorithms/java/src/mergedList/mergeSortedList.java new file mode 100644 index 00000000..1399ee8e --- /dev/null +++ b/algorithms/java/src/mergedList/mergeSortedList.java @@ -0,0 +1,39 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +package mergedList; + +public class mergeSortedList { + + static class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + ListNode current = dummy; + + while (l1 != null && l2 != null) { + if (l1.val < l2.val) { + current.next = l1; + l1 = l1.next; + } else { + current.next = l2; + l2 = l2.next; + } + current = current.next; + } + + current.next = (l1 != null) ? l1 : l2; + return dummy.next; + } +} \ No newline at end of file