描述
兩個(gè)排序鏈表合并為一個(gè)新的排序鏈表
樣例
給出 1->3->8->11->15->null,2->null, 返回 1->2->3->8->11->15->null。
注意
只判斷一次用if 多次判斷用while ,錯(cuò)用了就會報(bào)錯(cuò)
思路
新建一個(gè)當(dāng)前結(jié)點(diǎn)來構(gòu)造鏈表
代碼
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
tail.next = l1;
l1 = l1.next;
} else {
tail.next = l2;
l2 = l2.next;
}
// 不能忘記向后移動(dòng)當(dāng)前指針
tail = tail.next;
}
// 結(jié)點(diǎn)可以直接指向新的結(jié)點(diǎn)就把鏈表連接到一起了,數(shù)組不能這么做
// 如果用while會死循環(huán)
if (l1 != null) {
tail.next = l1;
}
if (l2 != null) {
tail.next = l2;
}
return dummy.next;
}
}