Description
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.
Examples
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
解题思路
我用的是傻办法hhhhhh
新建一个list,然后对两边进行判断,选取较小的那个放到新list里面,最后返回新list
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode s1, s2, t;
s1 = l1;
s2 = l2;
t = new ListNode(0);
t.next = l1;
ListNode h = t;
while(s1 != null && s2 != null){
t = t.next;
if(s1.val >= s2.val){
ListNode temp = s1.next;
s1.next = new ListNode(s2.val);
s1.next.next = temp;
s2 = s2.next;
}
s1 = s1.next;
}
if(s2 != null)
t.next = s2;
if(s1 != null)
t.next = s1;
return h.next;
}
}
其他方法
去discussion摸了一圈,有一个java跑了1ms的递归方法,哇下次要把递归也考虑进去!
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;
}
}
其他
- 做题的时候犯了傻,每次都返回 t -> next,导致只有只能返回一个值hhhhhh,看了半天才反应过来开始的时候应该有一个指向 t 的 head 用于最后的返回