原题链接:https://leetcode.com/problems/merge-two-sorted-lists/
思路:
0 处理边界条件
1 两个输入链表可能为空,采用dummy节点,使得dummy.next指向新链表的第一个节点。
2 初始化时,使用两个指针指向两个链表的表头,两个指针同时不为空时,取较小的节点放入新链表的尾部。
3 然后把链表中不为空的部分重新放到新链表的尾部。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//判断边界条件
if(l1==null && l2!=null)
return l2;
if(l1!=null && l2==null)
return l1;
if(l1==null && l2==null)
return null;
//创建头结点
ListNode head = new ListNode(0);
ListNode current = head;
while(l1!=null && l2!=null){
if(l1.val<=l2.val){//取较小值的节点
current.next = l1;
current = current.next;
l1 = l1.next;
}else{
current.next = l2;
current = current.next;
l2 = l2.next;
}
}
//将剩下的部分放置在合并后链表的尾部
if(l1!=null)
current.next= l1;
if(l2!=null)
current.next=l2;
return head.next;
}
}
什么情况下,我们需要使用dummy node?