LeetCode - 21 Merge Two Sorted Lists

作者 QIFAN 日期 2016-07-15
LeetCode - 21 Merge Two Sorted Lists

Difficulty:Easy

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.

思路

还是想了一会的,改怎么返回merge后的list。就是在最开始的时候建一个reference指向val最小的头就好了。然后比对每个node的val进行merge。

就是一定要在之前有个reference指向头。不然最后返回的只能是最后的那个node。
还有就是题目没写清楚sorted。我就默认升序了。

代码

/**
* 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;
if(l2==null) return l1;
ListNode l;
if(l1.val<=l2.val) {
l = l1;
merge(l1, l2);
} else {
l = l2;
merge(l2, l1);
}
return l;
}
// make sure that l2.val > l1.val
public void merge(ListNode l1, ListNode l2) {
if(l2==null) return;
while(l1.next != null && l1.next.val <= l2.val) {
l1 = l1.next;
}
ListNode temp = l1.next;
l1.next = l2;
merge(l1, temp);
}
}

原题链接:https://leetcode.com/problems/merge-two-sorted-lists/

Mark一记一次过。