16 合并两个排序的链表

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
 
 
递归:
合并1—3—5 2—4--6
例如 找出 要合并的2个链表中值小的 头结点1。1 指向 merge(3,5 2,4,6)
merge 返回的是已经合并好的链表


1→{3—5 2—4--6}
1→2->{3—5 4—6 }
..........
1-2-3-4-5-6



边界条件想清楚 不要想当然的写成
   if(p1==null) return null;
if(p2==null) return null;

正确的边界条件是 当p1 为空的时候,说明P1 已经没有元素了 ,这时候 应该把P2赋值给mhead.next, 所以返回的是p2

利用递归:
找到2个链表中,最小的头结点,合并后的链表头结点就是最小的头结点。
合并链表指向剩余部分。
 
 
 1 public class Solution {
 2     public ListNode Merge(ListNode p1,ListNode p2) {
 3         if(p1==null) return p2;
 4         if(p2==null) return p1;
 5         ListNode mhead = null;
 6         if(p1.val<p2.val){
 7             mhead = p1; mhead.next = Merge(p1.next,p2);
 8         }
 9         else{
10             mhead = p2;
11             mhead.next = Merge(p1,p2.next);
12         }
13         return mhead;
14     }
15 }

 

 

非递归 20180307

 

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode Merge(ListNode list1,ListNode list2) {
12         if(list1==null) return list2;
13         if(list2==null) return list1;
14         ListNode fakehead = new ListNode(-1);
15         ListNode cur = fakehead;
16         while (list1!=null && list2!=null)
17             if(list1.val<list2.val){
18                 cur.next = list1;
19                 cur = list1;
20                 list1 = list1.next;
21             }
22             else {
23                 cur.next = list2;
24                 cur = list2;
25                 list2 = list2.next;
26             }
27         if(list1!=null)
28             cur.next = list1;
29  
30         if(list2!=null)
31             cur.next = list2;
32         return fakehead.next;
33     }
34 }

 

 

posted @ 2017-11-16 10:10  乐乐章  阅读(156)  评论(0编辑  收藏  举报