# LeetCode初尝试-简单-2

xiaoxiao2021-02-28  6

# 21. 合并两个有序链表

/** * 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) { //递归 ListNode result=null; if(l1==null || l2==null){ if(l1==null && l2==null) return null; else return result=(l1==null ? l2 : l1); } if(l1.val<l2.val){ result=l1; result.next=mergeTwoLists(l1.next, l2); }else{ result=l2; result.next=mergeTwoLists(l1, l2.next); } return result; } }

/** * 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) { //循环 ListNode start=new ListNode(0); ListNode temp=new ListNode(0); start.next=temp; while(l1!=null && l2!=null){ if(l1.val<l2.val){ temp.next=l1; l1=l1.next; }else{ temp.next=l2; l2=l2.next; } temp=temp.next; } if(l1!=null) temp.next=l1; if(l2!=null) temp.next=l2; return start.next.next; } }