1+ package leetcode .editor .en ;
2+ 3+ import java .util .*;
4+ 5+ class MergeTwoSortedLists {
6+ 7+ //leetcode submit region begin(Prohibit modification and deletion)
8+ /**
9+ * Definition for singly-linked list.
10+ * public class ListNode {
11+ * int val;
12+ * ListNode next;
13+ * ListNode() {}
14+ * ListNode(int val) { this.val = val; }
15+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
16+ * }
17+ */
18+ class Solution {
19+ public ListNode mergeTwoLists (ListNode list1 , ListNode list2 ) {
20+ ListNode preOut = new ListNode (), current = preOut ;
21+ while (list1 != null && list2 != null ){
22+ if (list1 .val < list2 .val ){
23+ current .next = list1 ;
24+ current = current .next ;
25+ list1 = list1 .next ;
26+ } else {
27+ current .next = list2 ;
28+ current = current .next ;
29+ list2 = list2 .next ;
30+ }
31+ }
32+ ListNode longer = list1 != null ? list1 : list2 ;
33+ while (longer != null ){
34+ current .next = longer ;
35+ current = current .next ;
36+ longer = longer .next ;
37+ }
38+ return preOut .next ;
39+ }
40+ }
41+ //leetcode submit region end(Prohibit modification and deletion)
42+ 43+ public class ListNode {
44+ int val ;
45+ ListNode next ;
46+ ListNode () {}
47+ ListNode (int val ) { this .val = val ; }
48+ ListNode (int val , ListNode next ) { this .val = val ; this .next = next ; }
49+ }
50+ }
0 commit comments