File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ Problem: https://leetcode.com/problems/merge-two-sorted-lists/
3+ Description: return the head of the merged linked list of two sorted linked lists
4+ Concept: Linked List, Recursion
5+ Time Complexity: O(N+M), Runtime 0ms
6+ Space Complexity: O(1), Memory 42.74MB
7+ */
8+
9+ /**
10+ * Definition for singly-linked list.
11+ * public class ListNode {
12+ * int val;
13+ * ListNode next;
14+ * ListNode() {}
15+ * ListNode(int val) { this.val = val; }
16+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
17+ * }
18+ */
19+ class Solution {
20+ public ListNode mergeTwoLists (ListNode list1 , ListNode list2 ) {
21+
22+ ListNode head = new ListNode (0 );
23+ ListNode tail = head ;
24+
25+ while (list1 != null || list2 != null ) {
26+ if (list2 == null || (list1 != null && list1 .val <= list2 .val )) {
27+ tail = tail .next = new ListNode (list1 .val );
28+ list1 = list1 .next ;
29+ } else {
30+ tail = tail .next = new ListNode (list2 .val );
31+ list2 = list2 .next ;
32+ }
33+ }
34+ return head .next ;
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments