File tree 1 file changed +44
-0
lines changed
1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ /********************
2
+ // 021. Merge Two Sorted Lists
3
+ // Merge two sorted linked lists and return it as a new list.
4
+ // The new list should be made by splicing together the nodes of the first two lists.
5
+ // Example:
6
+ // Input: 1->2->4, 1->3->4
7
+ // Output: 1->1->2->3->4->4
8
+ ********************/
9
+
10
+ /**
11
+ * Definition for singly-linked list.
12
+ * public class ListNode {
13
+ * int val;
14
+ * ListNode next;
15
+ * ListNode(int x) { val = x; }
16
+ * }
17
+ */
18
+ class Solution {
19
+ public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
20
+ ListNode head = new ListNode(0);
21
+ ListNode p = head;
22
+
23
+ while(l1 != null && l2 != null) {
24
+ if(l1.val < l2.val) {
25
+ p.next = l1;
26
+ l1 = l1.next;
27
+ }else {
28
+ p.next = l2;
29
+ l2 = l2.next;
30
+ }
31
+ p = p.next;
32
+ }
33
+
34
+ if(l1 != null) {
35
+ p.next = l1;
36
+ }
37
+
38
+ if(l2 != null) {
39
+ p.next = l2;
40
+ }
41
+
42
+ return head.next;
43
+ }
44
+ }
You can’t perform that action at this time.
0 commit comments