Skip to content

Commit 4239431

Browse files
solves merge 2 linked lists
1 parent 8b64f35 commit 4239431

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
| 13 | [Roman To Integer](https://leetcode.com/problems/roman-to-integer/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/RomanToInteger.java) |
1010
| 14 | [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/LongestCommonPrefix.java) |
1111
| 20 | [ValidParentheses](https://leetcode.com/problems/valid-parentheses/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/ValidParentheses.java) |
12-
| 2 | []() | Easy | |
12+
| 21 | [Merge 2 Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | Easy | |
1313
| 2 | []() | Easy | |
1414
| 2 | []() | Easy | |
1515
| 2 | []() | Easy | |

src/Merge2SortedLists.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// https://leetcode.com/problems/merge-two-sorted-lists/
2+
3+
public class Merge2SortedLists {
4+
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
5+
ListNode result = new ListNode(-1);
6+
ListNode previous = result;
7+
8+
while (l1 != null && l2 != null) {
9+
if (l1.val <= l2.val) {
10+
previous.next = l1;
11+
l1 = l1.next;
12+
} else {
13+
previous.next = l2;
14+
l2 = l2.next;
15+
}
16+
previous = previous.next;
17+
}
18+
19+
previous.next = l1 == null ? l2 : l1;
20+
return result.next;
21+
}
22+
23+
public static class ListNode {
24+
int val;
25+
ListNode next;
26+
ListNode() {}
27+
ListNode(int val) { this.val = val; }
28+
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
29+
}
30+
}

0 commit comments

Comments
 (0)