本题思路很简单, 依次比较链表指针目前指向的结点的值, 将较小的值放到新链表中, 同时将链表指针更新, 直到其中一个链表为空, 那么接下来的就直接是另一个非空链表了.
/**
* 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 l = new ListNode(-1);
ListNode head = l;
if(l1 == null || l2 == null )
return l1 == null ? l2 : l1;
while(l1 != null && l2 != null) {
if(l1.val <= l2.val) {
l.next = l1;
l1 = l1.next;
} else {
l.next = l2;
l2 = l2.next;
}
l = l.next;
}
l.next = l1 == null? l2 :l1;
return head.next;
}
}
主要是为了记录一下大神的简介代码, 使用递归的方法 :
/**
* 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) {
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;
}
}
}
这里并没有新建立结点, 而是在原有的链表上进行连接操作. 很清晰的代码. 学习一下