将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
解法:
解法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; if (l2 == null) return l1; ListNode l0 = l1.val > l2.val ? l2 : l1; //分治思想,每次拿一个小的出来,每次的动作相同 l0.next = l1.val > l2.val ? mergeTwoLists(l1, l2.next) : mergeTwoLists(l1.next, l2); return l0; } }
解法二:
建立一个头结点,采用尾插的方法,一个一个的进行比较插入
/** * 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 p1,p2; p1 = l1; p2=l2; ListNode head = new ListNode(0); ListNode r = head; //if(!(l1 || l2)) return NULL; if(l1==null) return l2; if(l2==null) return l1; //合并 while(p1!=null && p2!=null){ if(p1.val <= p2.val){ r.next = p1; r = p1; p1 = p1.next; }else{ r.next = p2; r = p2; p2 = p2.next; } } if(p1==null){ r.next = p2; r = p2; } if(p2==null){ r.next = p1; r = p1; } return head.next; } }