[leetCode]剑指 Offer 25. 合并两个排序的链表
递归
可以逐一比较两个链表的头节点,将交小的节点取出放到链表尾部。当链表1为空时返回链表2,当链表2为空时,返回链表1。
/**
* 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) return l2;
else if(l2 == null) return l1;
ListNode pMergeHead = null;
if(l1.val >= l2.val){
pMergeHead = l2;
l2.next = mergeTwoLists(l1,l2.next);
}else{
pMergeHead = l1;
l1.next = mergeTwoLists(l1.next,l2);
}
return pMergeHead;
}
}
非递归写法,使用哑节点
两种写法思路一样,第二种简洁
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummyNode = new ListNode();
ListNode p1 = l1;
ListNode p2 = l2;
ListNode p = dummyNode;
while(p1 != null || p2 != null){
if(p1 == null){
p.next = p2;
break;
}else if(p2 == null){
p.next = p1;
break;
}
if(p1.val <= p2.val ){
p.next = p1;
p1 = p1.next;
p = p.next;
}else {
p.next = p2;
p2 = p2.next;
p =p.next;
}
}
return dummyNode.next;
}
}
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummyNode = new ListNode();
ListNode cur = dummyNode;
while(l1 != null && l2 != null){
if(l1.val <= l2.val ){
cur.next = l1;
l1 = l1.next;
}else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = l1 == null ? l2 : l1;
return dummyNode.next;
}
}