Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
思路:
双指针
注意:
1.合并时可以不用new新的ListNode节点,以节约空间;
2.前面可以不用判断l1, l2是否为空,因为后面的合并过程包含了。
3.跳出主循环后用if 而不用while
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode node = new ListNode(0);
ListNode result = node;
while(l1 !=null && l2 !=null){
if(l1.val < l2.val){
node.next = l1;
l1 = l1.next;
}else{
node.next = l2;
l2 = l2.next;
}
node = node.next;
}
if(l1!=null){
node.next = l1;
}
if(l2!=null){
node.next = l2;
}
return result.next;
}
}
网友评论