File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * public class ListNode {
4+ * int val;
5+ * ListNode next;
6+ * ListNode() {}
7+ * ListNode(int val) { this.val = val; }
8+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+ * }
10+ */
11+ class Solution {
12+ public ListNode mergeTwoLists (ListNode list1 , ListNode list2 ) {
13+ /**
14+ time: O(n + m)
15+ space: O(1)
16+ */
17+ if (list1 == null ) return list2 ;
18+ if (list2 == null ) return list1 ;
19+
20+ ListNode res = new ListNode ();
21+ ListNode tmp = res ;
22+
23+ while (list1 != null && list2 != null ) {
24+ if (list1 .val > list2 .val ) {
25+ tmp .next = list2 ;
26+ list2 = list2 .next ;
27+ } else {
28+ tmp .next = list1 ;
29+ list1 = list1 .next ;
30+ }
31+ tmp = tmp .next ;
32+ }
33+ if (list1 == null ) {
34+ tmp .next = list2 ;
35+ } else {
36+ tmp .next = list1 ;
37+ }
38+ return res .next ;
39+ }
40+ }
You can’t perform that action at this time.
0 commit comments