描述
输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
数据范围: 0 ≤n≤1000,−1000≤节点值≤1000
要求:空间复杂度 O(1),时间复杂度 O(n)
public ListNode Merge(ListNode head1,ListNode head2){
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
if(head1 == null)
return head2;
if(head2 == null)
return head1;
while(head1 != null && head2 != null){
if(head1.val <= head2.val){
cur.next = head1;
head1 = head1.next;
}
else{
cur.next = head2;
head2 = head2.next;
}
cur = cur.next;
}
cur.next = (head1 == null) ? head2 : head1;
return dummy.next;
}
该博客讨论了一个算法问题,即如何在O(1)的空间复杂度和O(n)的时间复杂度下合并两个递增有序的链表。提供的代码实现了这一功能,通过比较两个链表的当前节点值,将较小的节点添加到新链表中,直到其中一个链表为空,然后将非空链表连接到新链表的末尾,确保新链表仍然有序。
172万+

被折叠的 条评论
为什么被折叠?



