链表的类:
class ListNode{
int key;
ListNode next;
}
思路:
- 这个和数组不一样,不需要采用双指针,从后往前来
代码:
递归
public ListNode merge(ListNode head1,ListNode head2){
if(head1 == null){
return head2;
}else if(head2 == null){
return head1;
}
ListNode node = null;
if(head1.key < head2.key){
node =head1;
node.next = merge(head1.next,head2);
}else{
node = head2;
node.next = merge(head1,head2.next);
}
return node;
}
非递归
public ListNode merge(ListNode head1,ListNode head2){
if(head1 == null){
return head2;
}else if(head2 == null){
return head1;
}
ListNode node = null;
if(head1.key < head2.key){
node = head1;
head1 = head1.next;
}else{
node = head2;
head2 = head2.next;
}
while(head1 != null && head2 != null){
if(head1.key < head2.key){
node.next = head1;
head1 = head1.next;
}else{
node.next = head2;
head2 = head2.next;
}
}
if(head1 == null){
node = head2;
}
if(head2 == null){
node = head1;
}
return node;
}
时间: 2024-11-10 07:34:13