将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
//递归处理,将两个链表的节点顺次对比,小者加入结果尾部
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null||l2==null){
if(l1==null&&l2==null){
return null;
}else return l1==null?l2:l1;
}
ListNode result=null;//设置临时节点result
if(l1.val<l2.val){
result=l1;
result.next=mergeTwoLists(l1.next,l2);
}else{
result =l2;
result.next=mergeTwoLists(l1,l2.next);
}
return result;
}
}
剑指offer:this
需要新建一个链表节点,保存合并后的链表。但是新链表如何初始化呢?
有一个巧妙的思路:新建一个节点newNode, 并让表头val=-1;
ListNode newNode=new ListNode(-1);
然后用指针current操作这个链表。
ListNode current = newNode;//current 为指针,指向头节点newNode
最后返回这个链表我们需要的部分,即return newNode.next;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode pNode1=list1;
ListNode pNode2=list2;
ListNode newNode=new ListNode(-1);
ListNode current = newNode;//current是作为指针
while(pNode1!=null&&pNode2!=null){//新链表初始值
if(pNode1.val>pNode2.val){
current.next= pNode2;//对current指向节点的下一个节点赋值
pNode2=pNode2.next;
}else{
current.next=pNode1;
pNode1=pNode1.next;
}
current=current.next;//指针向后移动
}
//把未结束的链表连接到合并后的链表尾部
if(pNode1!=null){
current.next=pNode1;
}
if(pNode2!=null){
current.next=pNode2;
}
return newNode.next;
}
}
猜测:如果递归的话,是不是可以回避指针这个话题呢?因为递归的一层一层的list1.next= Merge(list1.next, list2);
如果用指针反而会麻烦。
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null){
return list2;
}
if(list2 == null){
return list1;
}
if(list1.val <= list2.val){
list1.next = Merge(list1.next, list2);
return list1;
}else{
list2.next = Merge(list1, list2.next);
return list2;
}
}
测试例子:
public static void main(String[] args) {
ListNode root = new ListNode(1);
ListNode three = new ListNode(3);
ListNode four = new ListNode(4);
ListNode eight = new ListNode(8);
ListNode then = new ListNode(2);
ListNode five = new ListNode(5);
ListNode nine = new ListNode(9);
root.next = three;
three.next=four;
four.next=eight;
eight.next=null;
then.next = five;
five.next=nine;
nine.next=null;
Merge(root,then);
}