File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Expand file tree Collapse file tree 1 file changed +46
-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+ * 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+ ListNode head = initNode (list1 , list2 );
14+ ListNode ptr = head ;
15+
16+ while (true ){
17+ if (list1 != null && list2 != null ) {
18+ if (list1 .val < list2 .val ) {
19+ ptr .val = list1 .val ;
20+ list1 = list1 .next ;
21+ } else {
22+ ptr .val = list2 .val ;
23+ list2 = list2 .next ;
24+ }
25+ }
26+ else if (list1 == null && list2 != null ) {
27+ ptr .val = list2 .val ;
28+ list2 = list2 .next ;
29+ }
30+ else if (list1 != null && list2 == null ) {
31+ ptr .val = list1 .val ;
32+ list1 = list1 .next ;
33+ }
34+ if (list1 == null && list2 == null ) break ;
35+ ptr .next = new ListNode ();
36+ ptr = ptr .next ;
37+ }
38+ return head ;
39+ }
40+
41+ public ListNode initNode (ListNode list1 , ListNode list2 ) {
42+ if (list1 == null && list2 == null ) return null ;
43+ return new ListNode ();
44+ }
45+ }
46+
You can’t perform that action at this time.
0 commit comments