Created
May 17, 2021 03:35
-
-
Save adeydas/7e0572bab8c1c71711f179ca69702171 to your computer and use it in GitHub Desktop.
Merge Two Sorted Lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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; } | |
| * } | |
| */ | |
| // https://leetcode.com/problems/merge-two-sorted-lists/ | |
| class Solution { | |
| public ListNode mergeTwoLists(ListNode l1, ListNode l2) { | |
| ListNode merged = new ListNode(Integer.MIN_VALUE, null); | |
| ListNode result = merged; | |
| while (l1 != null && l2 != null) { | |
| if (l1.val < l2.val) { | |
| merged.next = new ListNode(l1.val, null); | |
| l1 = l1.next; | |
| } else { | |
| merged.next = new ListNode(l2.val, null); | |
| l2 = l2.next; | |
| } | |
| merged = merged.next; | |
| } | |
| // if lists are uneven in length | |
| if (l1 != null) { | |
| merged.next = l1; | |
| } | |
| if (l2 != null) { | |
| merged.next = l2; | |
| } | |
| return result.next; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment