LeetCode第21题:将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出: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) {
ListNode head = new ListNode(0);
ListNode cur = head;
while(l1 != null && l2 != null){
int value;
if(l1.val < l2.val){
value = l1.val;
l1 = l1.next;
}else{
value = l2.val;
l2 = l2.next;
}
cur.next = new ListNode(value);
cur = cur.next;
}
while(l1 != null){
cur.next = new ListNode(l1.val);
l1 = l1.next;
cur = cur.next;
}
while(l2 != null){
cur.next = new ListNode(l2.val);
l2 = l2.next;
cur = cur.next;
}
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) {
ListNode head = new ListNode(0);
ListNode pre = head;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
pre.next = l1;
l1 = l1.next;
}else{
pre.next = l2;
l2 = l2.next;
}
pre = pre.next;
}
pre.next = l1 ==null ? l2 : l1;
return head.next;
}
}