这题属于简单题,题目也确实比较简单,这题直接用暴力解法是可以的,并不需要太多复杂的技巧。我在做的时候想的比较久的是base case的写法,不知道怎么使代码变得简洁,会担心漏掉情况,所以整体代码比较冗余,下面是我得代码:
/**
* 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) {
if (l1==null&&l2!=null){
return l2;
}
if (l2==null&&l1!=null){
return l1;
}
if (l1==null&&l2==null){
return l1;
}
ListNode cur = new ListNode();
ListNode res ;
res = cur;
while (l1 != null && l2 != null){
if (l1.val<l2.val){
cur.next = l1;
cur = cur.next;
l1 = l1.next;
}else {
cur.next = l2;
cur = cur.next;
l2 = l2.next;
}
}
if (l1!=null&&l2 == null){
cur.next = l1;
}
if (l1 == null&&l2 != null){
cur.next = l2;
}
cur = res.next;
res.next = null;
return cur;
}
}
?成绩如下:
?官方给出的解法中的coding很值得我学习:
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode prehead = new ListNode(-1);
ListNode prev = prehead;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
prev.next = l1;
l1 = l1.next;
} else {
prev.next = l2;
l2 = l2.next;
}
prev = prev.next;
}
// 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
prev.next = l1 == null ? l2 : l1;
return prehead.next;
}
}
给出的递归解法是我没想到的:
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
} else if (l2 == null) {
return l1;
} else if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
|