LeetCode之两有序列表合并
自己卡在某个死角
问题
ListNode head=null;
head=l1;
l1=l1.next;
head=head.next;
以上代码 导致 我最好拿到head是链表的末尾,而链表又是单链表,不能逆转
解决方案
new一个空的head,然后操作head的next
public ListNode headMergeTwoLists(ListNode l1, ListNode l2) {
ListNode dump = new ListNode(0);
ListNode cur = dump;
while(l1 != null || l2 != null) {
if(l1 == null) {
cur.next = l2;
l2 = l2.next;
}else if (l2 == null) {
cur.next = l1;
l1 = l1.next;
}else if(l1.val < l2.val){
cur.next = l1;
l1 = l1.next;
}else{
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
return dump.next;
}
- 总结
第一轮的时候,cur持有的是dump引用,然后对cur.next赋值 ,其实就是对dump.next赋值,然后通过cur这边变量作为中转,将l1,l2链表搬移到 dump链上面
递归
- 代码
public ListNode recursionMergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode header = null;
if (l1.val <= l2.val) {
header = l1;
header.next = recursionMergeTwoLists(l1.next, l2);
} else {
header = l2;
header.next = recursionMergeTwoLists(l1, l2.next);
}
return header;
}
- 总结:
- 怎么递归能形成链表
分析递归过程:
1. new 一个链表对象
2. 赋值
3. 递归给链表 next对象赋值
这样链表就形成,每次递归的时候,都是在给上一个链表节点next赋值(链表头例外),然后递归的给自己节点next赋值 - 为什么返回链表的头
1. 递归的时候,是从最底层开发返回,要返回到最外层,所以返回的是最外的header对象,最外层的header对象就是链表头
总结下:说白就是用递归的返回的特性,实现单项列表,正向的遍历后,逆向返回过程 - 盗用一张别人图,分析过程
- 怎么递归能形成链表
- 借鉴博客: CSDN
不得不吐槽下自己
以上方案都是百度到,而不是自己想到的,这么简单的题目,卡了很久,不得不反省下自己