Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
思路:首先创建一个空链表l3,如果比较l1和l2的大小,如果l1.val>l2.val,则将l2,链接到l3上,将l2向后移一个,否则就相反
代码如下(已通过leetcode)
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2==null) return l1;
ListNode p=l1;
ListNode q=l2;
ListNode a;
if(p.val>q.val) {
a=q;
q=q.next;
} else {
a=p;
p=p.next;
}
ListNode ans=a;
while(p!=null && q!=null) {
if(p.val>q.val) {
a.next=q;
q=q.next;
a=a.next;
} else {
a.next=p;
p=p.next;
a=a.next;
}
}
while(p!=null) {
a.next=p;
p=p.next;
a=a.next;
}
while(q!=null) {
a.next=q;
q=q.next;
a=a.next;
}
return ans;
}
}