合并两个有序链表(剑指offer-16)

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

解答
方法1:递归

 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         if(list1 == null && list2 == null) return null;//递归终止条件
15         ListNode head = null;
16         if(list1.val>=list2.val){
17             head = list2;
18             list2.next = Merge(list1,list2.next);}
19         else{
20             head = list1;
21             list1.next = Merge(list1.next,list2);}
22         return head;
23     }
24 }

 

 


图片引用自:https://blog.csdn.net/fengpojian/article/details/81384130

方法2:迭代

 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         ListNode head = new ListNode(-1);
13         ListNode cur = head;
14         while (list1 != null && list2 != null) {
15         if (list1.val <= list2.val) {
16             cur.next = list1;
17             list1 = list1.next;
18         } else {
19             cur.next = list2;
20             list2 = list2.next;
21         }
22         cur = cur.next;
23         }
24         if (list1 != null)
25             cur.next = list1;
26         if (list2 != null)
27             cur.next = list2;
28         return head.next;
29     }
30 }

 

posted @ 2020-07-02 17:15  10000_Hours  阅读(127)  评论(0编辑  收藏  举报