問題:
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.
大意:
合并兩個有序鏈表并返回一個新鏈表。新鏈表應該包含原先兩個鏈表中全部節(jié)點。
思路:
合并兩個有序的鏈表其實思路還挺直接的,從兩個鏈表的第一個節(jié)點開始比較大小,將小的那個放到新鏈表里,然后后移繼續(xù)比較,大概思路就是這樣,只是實現(xiàn)起來麻煩一點。另外其實還想到了一個奇葩的思路,就是將兩個鏈表中的鍵值放到一個數(shù)組中,對數(shù)組進行排序,然后將數(shù)組里的元素按順序放到新建的節(jié)點里去然后放入一個新鏈表就可以了哈哈哈。
代碼(Java):
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
else if (l2 == null) return l1;
ListNode result;
ListNode mark;
if (l1.val <= l2.val) {
result = l1;
l1 = l1.next;
} else {
result = l2;
l2 = l2.next;
}
mark = result;
while (l1 != null) {
if (l2 != null && l2.val < l1.val) {
mark.next = l2;
mark = mark.next;
l2 = l2.next;
} else {
mark.next = l1;
mark = mark.next;
l1 = l1.next;
}
}
if (l2 != null) mark.next = l2;
return result;
}
}
他山之石:
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
這個方法的思路其實差不多,但是用的是遞歸的方式。耗時1ms,而上面我的代碼耗時16ms,真的有這么大的差異么。。。
合集:https://github.com/Cloudox/LeetCode-Record