【LeetCode从零单排】No21.MergeTwoSortedLists

/** * Definition for singly-linked list. * public class ListNode { *int val; *ListNode next; *ListNode(int x) { *val = x; *next = null; *} * } */public class Solution {public ListNode mergeTwoLists(ListNode l1, ListNode l2) {//判断三种null情况if(l1==null && l2==null) return l1;if(l1==null && l2!=null) return l2;if(l1!=null && l2==null) return l1;//定义头指针if(l1.val<=l2.val){//分别对l1和l2取当前和下一节点指针ListNode first=l1;ListNode second=l1.next;ListNode l2_temp=l2;ListNode l2_second=l2.next;//l2插向l1while(l2_temp!=null){if(second!=null){if(l2_temp.val>=first.val && l2_temp.val<=second.val){first.next=l2_temp;l2_temp.next=second;first=first.next;second=first.next;//这个try catch是指当l2_second=null时,l2_second.next是空指针,这时已经排序结束,所以returntry{l2_temp=l2_second;l2_second=l2_second.next;}catch (Exception e){return l1;}}else{first=first.next;second=first.next;}}else{first.next=l2_temp;return l1;}}return l1;}else{ListNode first=l2;ListNode second=l2.next;ListNode l1_temp=l1;ListNode l1_second=l1.next;while(l1_temp!=null){if(second!=null){if(l1_temp.val>=first.val && l1_temp.val<=second.val){first.next=l1_temp;l1_temp.next=second;first=first.next;second=first.next;try{l1_temp=l1_second;l1_second=l1_second.next;}catch (Exception e){return l2;}}else{first=first.next;second=first.next;}}else{first.next=l1_temp;return l2;}}return l2;}}}

代码下载:https://github.com/jimenbian/GarvinLeetCode

/********************************

* 本文来自博客 “李博Garvin“

* 转载请标明出处:

******************************************/

,自己不喜欢的人,可以报之以沉默微笑;

【LeetCode从零单排】No21.MergeTwoSortedLists

相关文章:

你感兴趣的文章:

标签云: