LeetCode(21) - Merge Two Sorted Lists

  题目要求是,给你两个sorted LinkedList,然后把它们两个合并成一个新的LinkedList。思路很简单,就是比较ListNode L1 和 L2,哪个小就把那个node放到新的list里,并且移动相应ListNode的指针(L1或L2)。注意其中一个为null,另外一个不为null的时候别漏掉就好。

  代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
11         //一般来说,当需要处理head时,我都会选择用一个dumpNode,省去很多不必要的麻烦。
12         ListNode dumpNode = new ListNode(0);
13         ListNode curr = dumpNode;
14         while (l1 != null && l2 != null) {
15             //判断大小,小的值加到新的list里。
16             if (l1.val < l2.val) {
17                 curr.next = new ListNode(l1.val);
18                 l1 = l1.next;
19             }
20             else {
21                 curr.next = new ListNode(l2.val);
22                 l2 = l2.next;
23             }
24             curr = curr.next;
25         }
26         
27         //注意上面循环走完其中一个可能仍不为null。
28         while (l1 != null) {
29             curr.next = new ListNode(l1.val);
30             l1 = l1.next;
31             curr = curr.next;
32         }
33         
34         while (l2 != null) {
35             curr.next = new ListNode(l2.val);
36             l2 = l2.next;
37             curr = curr.next;
38         }
39         //返回head。
40         return dumpNode.next;
41     }
42 }
原文地址:https://www.cnblogs.com/kepuCS/p/5278410.html