描述
输入两个递增的链表,单个链表的长度为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;
}