題目
題解
題解1
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode p = dummy;
ListNode p1 = l1;
ListNode p2 = l2;
while (p1 != null && p2 != null) {
if (p1.val < p2.val) {
p.next = p1;
p = p.next;
p1 = p1.next;
} else {
p.next = p2;
p = p.next;
p2 = p2.next;
}
}
while (p1 != null) {
p.next = p1;
p = p.next;
p1 = p1.next;
}
while (p2 != null) {
p.next = p2;
p = p.next;
p2 = p2.next;
}
return dummy.next;
}
}