首页 > 代码库 > Merge Two Sorted Lists
Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * }10 * }11 */12 public class Solution {13 public ListNode mergeTwoLists(ListNode l1, ListNode l2) {14 15 if (l1==null || l2==null) {16 if (l1 != null) {17 return l1;18 }19 if (l2 != null) {20 return l2;21 }22 return null;23 }24 ListNode first;25 ListNode curr;26 if (l1.val < l2.val) {27 curr=l1;28 l1=l1.next;29 }else {30 curr=l2;31 l2=l2.next;32 }33 first=curr;34 while (l1!=null && l2!=null) {35 if (l1.val<l2.val) {36 curr.next=l1;37 l1=l1.next;38 curr=curr.next;39 }else {40 curr.next=l2;41 l2=l2.next;42 curr=curr.next;43 }44 }45 if (l1!=null) {46 curr.next=l1;47 }48 if (l2!=null) {49 curr.next=l2;50 }51 return first;52 }53 }
Merge Two Sorted Lists
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。