高质量代码-并和链表

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

 

解决:

 1 public class Solution {
 2     //实现了原址并和,复杂度O(n)
 3     public ListNode Merge(ListNode list1,ListNode list2) {
 4         //两个链表有一个为空则返回另一个非空链表
 5         if (list1 == null && list2 == null) {
 6             return null;
 7         } else if (list1 == null) {
 8             return list2;
 9         } else if (list2 == null) {
10             return list1;
11         }
12         //head指向并和链表的头结点,tem指向新增的节点
13            ListNode head, tem;
14         //选出两个链表第一个元素大的节点做为新链表的头结点
15         if (list1.val <= list2.val) {
16             head = list1;
17             tem = head;
18             list1 = list1.next;
19         } else {
20             head = list2;
21             tem = head;
22             list2 = list2.next;
23         }
24         //两个链表中小的元素加入到新链表的尾部,终止条件:两个链表有一个为空
25         while (list1 != null && list2 != null) {
26             if (list1.val <= list2.val) {
27                 tem.next = list1;
28                 list1 = list1.next;
29                  tem = tem.next;
30             } else {
31                 tem.next = list2;
32                 list2 = list2.next;
33                 tem = tem.next;
34             }
35         }
36         //添加剩余未添加的节点
37         while (list1 != null) {
38             tem.next = list1;
39             tem = tem.next;
40             list1 = list1.next;
41         }
42         while (list2 != null) {
43             tem.next = list2;
44             tem = tem.next;
45             list2 = list2.next;
46         }
47         tem.next = null;
48         return head;
49         
50     }
51 }

 

posted @ 2016-04-02 10:22  gatsbydhn  阅读(147)  评论(0编辑  收藏  举报