描述
首先看链表结构:
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
本题目要求把传入两个链表,根据每个元素的val大小,按顺序把两个链表重新组装起来,组装为一个链表。
比如1-3-5-7和2-4-6-8两个链表,组装起来就是1-2-3-4-5-6-7-8
答案描述
先看看我的答案,巨长无比还不好理解,想法是这样的:就是根据两个链表遍历比大小,新建一个新的链表---分别用指针遍历两个链表,对比当前元素,哪个小就把哪个的值传入新联表的新建元素中,然后后移一位。
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}else if(l2 == null) return l1;
boolean bool = false;
ListNode l0 = new ListNode(0);
ListNode first = l0;
while(true){
if(l1.val<l2.val){
l0.next = new ListNode(l1.val);
l0 = l0.next;
if(l1.next == null){
bool = true;
break;
}
l1 = l1.next;
}else{
l0.next = new ListNode(l2.val);
l0 = l0.next;
if(l2.next == null) break;
l2 = l2.next;
}
}
if(bool){
while(true){
l0.next = new ListNode(l2.val);
l0 = l0.next;
if(l2.next == null) break;
l2 = l2.next;
}
}else{
while(true){
l0.next = new ListNode(l1.val);
l0 = l0.next;
if(l1.next == null) break;
l1 = l1.next;
}
}
return first.next;
}
}
再看看人家大神的方法,用的是递归,超级好懂,我对我的想法无力吐槽:
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
ListNode mergeHead;
if(l1.val < l2.val){
mergeHead = l1;
mergeHead.next = mergeTwoLists(l1.next, l2);
}
else{
mergeHead = l2;
mergeHead.next = mergeTwoLists(l1, l2.next);
}
return mergeHead;
}
}
这就是差距。。。