[LC]21题 Merge Two Sorted Lists (合并两个有序链表)(链表)

时间:2019-09-27
本文章向大家介绍[LC]21题 Merge Two Sorted Lists (合并两个有序链表)(链表),主要包括[LC]21题 Merge Two Sorted Lists (合并两个有序链表)(链表)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

①英文题目

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

②中文题目

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

③思路

   就是判断大小,注意,比着比着,l1或者l2就会空掉,然后导致空指针的问题,进而报错。

④代码

 1 class Solution {
 2     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
 3         ListNode zf=null;
 4        // ListNode curr=zf;
 5         ListNode temp1=l1;
 6         ListNode temp2=l2;
 7         if(temp1==null&&temp2!=null){
 8               zf=temp2;
 9             temp2=temp2.next;
10          }
11         if(temp1!=null&&temp2==null){
12             zf=temp1;
13             temp1=temp1.next;
14         }                              
15         if(temp1!=null&&temp2!=null){
16             if(temp1.val<temp2.val){
17               zf=temp1;
18               temp1=temp1.next;
19             } 
20         else{
21               zf=temp2;     
22               temp2=temp2.next;
23             }
24         }                         //到此,zf是最小的结点,也是头部。
25         ListNode curr=zf;
26         while(temp1!=null||temp2!=null){
27             if(temp1==null&&temp2!=null){
28                 curr.next=temp2;
29                 temp2=temp2.next;
30                 curr=curr.next;
31             }
32             if(temp2==null&&temp1!=null){
33                 curr.next=temp1;
34                 temp1=temp1.next;
35                 curr=curr.next;
36             }  
37             if(temp1!=null&&temp2!=null&&temp1.val<temp2.val){
38                 curr.next=temp1;
39                 temp1=temp1.next;
40                 curr=curr.next;
41             }
42             if(temp1!=null&&temp2!=null&&temp1.val>=temp2.val){
43                 curr.next=temp2;
44                 temp2=temp2.next;
45                 curr=curr.next;
46             }       
47         }
48     return zf; 
49     }
50 }

⑤学到的知识

    1、如果超时,那去考虑是不是while()的括号里写的表达式,一直跳不出while循环。

   2、DriverSolution__.__helper__这种报错,是空指针。一般就是某个链表已经到链尾了,代码还在找它的next,从而导致空指针。

原文地址:https://www.cnblogs.com/zf007/p/11595452.html