File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * public class ListNode {
4
+ * public int val;
5
+ * public ListNode next;
6
+ * public ListNode(int val=0, ListNode next=null) {
7
+ * this.val = val;
8
+ * this.next = next;
9
+ * }
10
+ * }
11
+ */
12
+ public class Solution
13
+ {
14
+ public ListNode MergeTwoLists ( ListNode l1 , ListNode l2 )
15
+ {
16
+ ListNode curr = new ListNode ( 0 ) ;
17
+ ListNode dummy = curr ;
18
+
19
+ while ( l1 != null && l2 != null )
20
+ {
21
+ if ( l1 . val < l2 . val )
22
+ {
23
+ curr . next = l1 ;
24
+ l1 = l1 . next ;
25
+ }
26
+ else
27
+ {
28
+ curr . next = l2 ;
29
+ l2 = l2 . next ;
30
+ }
31
+ curr = curr . next ;
32
+ }
33
+
34
+ curr . next = l1 ?? l2 ;
35
+
36
+ return dummy . next ;
37
+ }
38
+ }
39
+
40
+ /** SOLUTION TWO **/
41
+
42
+ public class Solution {
43
+ public ListNode MergeTwoLists ( ListNode list1 , ListNode list2 ) {
44
+ ListNode dummy = new ListNode ( - 1 ) ;
45
+ ListNode current = dummy ;
46
+
47
+ while ( list1 != null && list2 != null ) {
48
+ if ( list1 . val < list2 . val ) {
49
+ current . next = list1 ;
50
+ list1 = list1 . next ;
51
+ } else {
52
+ current . next = list2 ;
53
+ list2 = list2 . next ;
54
+ }
55
+ current = current . next ;
56
+ }
57
+
58
+ if ( list1 != null ) {
59
+ current . next = list1 ;
60
+ }
61
+
62
+ if ( list2 != null ) {
63
+ current . next = list2 ;
64
+ }
65
+
66
+ return dummy . next ;
67
+ }
68
+ }
You can’t perform that action at this time.
0 commit comments