描述
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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
思路
使用循环遍历的方式,将两个链表合并成为一个链表。每次合并之前都进行一次比较操作。
/**
* 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) {
//使用-1作为头部节点,返回链表为头部节点的下一个节点
ListNode out = new ListNode(-1);
ListNode cur = out;
while(l1 != null && l2 != null){
//比较并创建节点,加入链表
ListNode new_node;
if(l1.val < l2.val){
new_node = new ListNode(l1.val);
l1 = l1.next;
}else{
new_node = new ListNode(l2.val);
l2 = l2.next;
}
cur.next = new_node;
cur = cur.next;
}
//将剩下的节点拼接在链表后面
if(l1 != null){
cur.next = l1;
}else{
cur.next = l2;
}
return out.next;
}
}Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Two Sorted Lists.
Memory Usage: 39.3 MB, less than 17.51% of Java online submissions for Merge Two Sorted Lists.
另一种思路
使用递归的方法,将两个链表进行合并操作。
但是递归会导致程序效率变低。
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;
}
}
}Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Two Sorted Lists.
Memory Usage: 39.3 MB, less than 17.51% of Java online submissions for Merge Two Sorted Lists.