题目: 合并两个已经有序的链表
分析:如果其中任何一个链表为空的话,就返回另一个链表的链表头,如果均不为空的话就比较哪个小,然后就用小的那个作为链表的头,运用递归的手法逐渐递归下去即可合并两个链表。
代码如下:
package problem2;
/**
* @author Hutongling
*/
public class 合并两个排序的链表 {
static Node mergeTwoSortedList(Node head1,Node head2){
if(head1==null && head2==null)
return null;
if(head1==null && head2!=null)
return head2;
if(head2==null && head1!=null)
return head1;
Node head=null;
if(head1.value<head2.value){
head=head1;
head1.next=mergeTwoSortedList(head1.next,head2); //递归
}else{
head=head2;
head2.next=mergeTwoSortedList(head1,head2.next); //递归
}
return head;
}
public static void main(String[] args) {
int data1[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,20,30};
int data2[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,20,30};
Node head1=new Node(data1[0]); //新建链表的头结点
Node head1_1=head1; //保留链表的头结点
for(int i=1;i<data1.length;i++){ //用尾插法创建一个链表
Node node1=new Node(data1[i]);
head1.next=node1;
head1=node1;
}
Node head2=new Node(data2[0]); //新建链表的头结点
Node head2_1=head2; //保留链表的头结点
for(int i=1;i<data2.length;i++){ //用尾插法创建一个链表
Node node1=new Node(data2[i]);
head2.next=node1;
head2=node1;
}
Node node=mergeTwoSortedList(head1_1,head2_1);
while(node.next!=null){
System.out.print(node.value + " ");
node=node.next;
}
System.out.println(node.value);
}
}
Node节点的创建见:http://blog.csdn.net/hutongling/article/details/62889440
代码结果如下:
1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 12 13 13 14 14 15 15 20 20 30 30