将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
public static ListNode mergeTwoLists(ListNode l1,ListNode l2){ ListNode dumb=new ListNode(0); ListNode head=dumb; while (l1!=null&&l2!=null){ if(l1.val<l2.val){ dumb.next=l1; l1=l1.next; }else{ dumb.next=l2; l2=l2.next; } dumb=dumb.next; } dumb.next=(l1==null?l2:l1); return head.next; }
思路:
1.定义一个哑节点,一个新链表的头节点(开始等于哑节点)。
2.遍历要合并的2个链表,对比2个节点将小的节点存在哑节点的后一个,当有一个链表遍历到尾节点后退出循环。
3.退出循环后判断哪个链表没有到尾节点,拼接到哑节点的下一个节点。