016 合并两个排序的链表

1.题目

  输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

2.分析

  

3.程序

 1 package first;
 2 
 3 import java.util.ArrayList;
 4 
 5 public class Merge {
 6     public static void main(String[] args){
 7         //第一个链表
 8         ListNode head = new ListNode();
 9         ListNode second = new ListNode();
10         ListNode third = new ListNode();
11         ListNode forth = new ListNode();
12         head.next = second;
13         second.next = third;
14         third.next = forth;
15         head.val = 1;
16         second.val = 2;
17         third.val = 3;
18         forth.val = 4;
19         //第二个链表
20         ListNode head2 = new ListNode();
21         ListNode second2 = new ListNode();
22         ListNode third2 = new ListNode();
23         ListNode forth2 = new ListNode();
24         head2.next = second2;
25         second2.next = third2;
26         third2.next = forth2;
27         head2.val = 3;
28         second2.val = 4;
29         third2.val = 5;
30         forth2.val = 6;
31         //打印出来
32         ListNode listNode=Merge2(head,head2);
33         ArrayList list=printListFromTailToHead(listNode);
34         printInfo(list);
35 
36     }
37 
38     /**
39      * 非递归
40      */
41     static ArrayList<Integer> arrayList=new ArrayList<Integer>();
42     public static ListNode Merge(ListNode list1,ListNode list2) {
43         ListNode newHead = new ListNode(-1);
44         ListNode current = newHead;
45         while (list1 != null && list2 != null) {
46             if (list1.val < list2.val) {
47                 current.next = list1;
48                 list1 = list1.next;
49             } else {
50                 current.next = list2;
51                 list2 = list2.next;
52             }
53             current = current.next;
54         }
55         if (list1 != null) current.next = list1;
56         if (list2 != null) current.next = list2;
57         return newHead.next;
58     }
59 
60     /**
61      * 递归
62      */
63     public static ListNode Merge2(ListNode list1,ListNode list2) {
64         if (list1 == null) return list2;
65         if (list2 == null) return list1;
66         if (list1.val < list2.val) {
67             list1.next = Merge(list1.next, list2);
68             return list1;
69         } else {
70             list2.next = Merge(list1, list2.next);
71             return list2;
72         }
73     }
74 
75     public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
76         if(listNode!=null){
77             printListFromTailToHead(listNode.next);
78             arrayList.add(listNode.val);
79         }
80         return arrayList;
81     }
82 
83     public static void printInfo(ArrayList list) {
84         for(int i=0;i<list.size();i++) {
85             System.out.print(list.get(i)+" ");
86         }
87         System.out.println("");
88     }
89 
90 }

猜你喜欢

转载自www.cnblogs.com/juncaoit/p/10435654.html