forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path(Leetcode)merge-two-sorted-lists.java
51 lines (41 loc) · 1.2 KB
/
(Leetcode)merge-two-sorted-lists.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// 21. Merge two sorted linked lists
// https://leetcode.com/problems/merge-two-sorted-lists/
//Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
// Input: l1 = [1,2,4], l2 = [1,3,4]
// Output: [1,1,2,3,4,4]
// ---- Solution -----
/**
* 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; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode();
ListNode p = head;
ListNode n1 = l1;
ListNode n2 = l2;
while (n1 != null && n2 != null) {
if (n1.val > n2.val) {
p.next = n2;
n2 = n2.next;
} else {
p.next = n1;
n1 = n1.next;
}
p = p.next;
}
if (n1 != null) {
p.next = n1;
}
if (n2 != null) {
p.next = n2;
}
return head.next;
}
}