融合链表

 1 package com.algorithm;
 2 
 3 public class MergeList {
 4       public ListNode Merge(ListNode list1,ListNode list2) {
 5           //运行时间:32ms
 6           //占用内存:688k
 7           //输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
 8           //第一次比较
 9           if(list1 == null) 
10               return list2;
11           if(list2 == null) 
12               return list1;
13           ListNode listGuard = null;//哨兵,存储链表头指针
14           ListNode listroot = null;
15           //然后每次比较两条链表的每一个结点的大小,如果小的,那么将哨兵的next指向它,再
16           //将小的节点指向next
17           if(list1.val <= list2.val) {
18               listroot = list1;
19               listGuard = list1;
20               list1 = list1.next;
21           }else{
22               listroot = list2;
23               listGuard = list2;
24               list2 = list2.next;
25           }
26           while(list1 != null && list2 != null){
27               if(list1.val <= list2.val){//如果第一条链表小于第二条链表
28                   listGuard.next = list1;
29                   listGuard = list1;
30                   list1 = list1.next;
31               }else{
32                   listGuard.next = list2;
33                   listGuard = list2;
34                   list2 = list2.next;
35               }
36           }
37           //循环遍历完了,如果第一个不等于空,则说明后面还有数据,直接移动指针listGuard即可
38           if(list1 != null) {
39               listGuard.next = list1;42           }
43           if(list2 != null) {
44               listGuard.next = list2;47           }
48           return listroot;
49         }
50       public static void main(String[] args) {
51              ListNode la = new ListNode(1);
52               ListNode lb = new ListNode(3);
53               ListNode lc = new ListNode(9);
54               la.next = lb;
55               lb.next = lc;
56               lc.next = null;
57               ListNode ma = new ListNode(4);
58               ListNode mb = new ListNode(6);
59               ListNode mc = new ListNode(7);
60               ma.next = mb;
61               mb.next = mc;
62               mc.next = null;
63               ListNode root = new MergeList().Merge(la,ma);
64               while(root!=null){
65                   System.out.print(root.val + " ");
66                   root = root.next;
67               }
68         }
69 }
70 public class ListNode { 71 int val; 72 ListNode next = null; 73 74 ListNode(int val) { 75 this.val = val; 76 } 77 }
 1   //递归
 2         if(list1 == null)
 3         return list2;
 4        if(list2 == null)
 5         return list1;
 6        if(list1.val <= list2.val){
 7             list1.next = Merge(list1.next, list2);
 8             return list1;
 9         }else{
10             list2.next = Merge(list1, list2.next);
11             return list2;
12         }

 

 

posted @ 2017-03-08 12:42  fankongkong  阅读(261)  评论(0编辑  收藏  举报