合并两个已经有序的链表

题目: 合并两个已经有序的链表
分析:如果其中任何一个链表为空的话,就返回另一个链表的链表头,如果均不为空的话就比较哪个小,然后就用小的那个作为链表的头,运用递归的手法逐渐递归下去即可合并两个链表。

代码如下:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值