题目链接
https://leetcode.cn/problems/merge-two-sorted-lists/
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
//方法1
if(list1==null) return list2;
if(list2==null) return list1;
ListNode res=list1.val<list2.val?list1:list2;
res.next=mergeTwoLists(res.next,list1.val>=list2.val?list1:list2);
return res;
//方法2
ListNode dumpyHead=new ListNode(-1);
ListNode cur=dumpyHead;
while(list1!=null && list2!=null)
{
if(list1.val<list2.val)
{
cur.next=list1;
cur=cur.next;
list1=list1.next;
}else
{
cur.next=list2;
cur=cur.next;
list2=list2.next;
}
}
if(list1==null)
{
cur.next=list2;
}else
{
cur.next=list1;
}
return dumpyHead.next;
}
}