首页 > 代码库 > 递归实现两个有序链表的合并

递归实现两个有序链表的合并

package com.wyl.linklist;

/**
 * 合并两个链表
 * @author wyl
 */
public class MergeLinkList {

    /**
     * 内部类,链表节点的结构
     * @author wyl
     *
     */
    public static class Node{
        private int val; //节点值
        private Node next; //节点的后继节点
        public Node(){
        }
        public Node(int val){
            this(val,null);
        }
        public Node(int val,Node next){
            this.val = val;
            this.next = next;
        }
        public int getVal() {
            return val;
        }
        public void setVal(int val) {
            this.val = val;
        }
        public Node getNext() {
            return next;
        }
        public void setNext(Node next) {
            this.next = next;
        }
    }
    /**
     * 递归实现两个排序链表的合并
     * @param l1
     * @param l2
     * @return
     */
    public Node merge(Node l1, Node l2){
        Node node = null;
        if(l1 == null || l2 == null){
            return l1==null?l2:l1;
        } else if(l1 != null || l2 != null){
            if(l1.val < l2.val){
                node = l1;
                node.next = merge(l1.next, l2);
            }else{
                node = l2;
                node.next = merge(l1, l2.next);
            }
        }
        return node;
    }
    public static void main(String[] args) {
        
        MergeLinkList mergeLinkList = new MergeLinkList();
        Node node = new Node(10); //存储排序好的偶数值节点
        for(int i=10; i>0; i=i-2){
            node = new Node(i, node);
        }
        
        Node node2 = new Node(15);//存储排序好的奇数值节点
        for(int i=15; i>0; i=i-2){
            node2 = new Node(i, node2);
        }
        
//        Node n = mergeLinkList.merge(node, node2);
//        Node n = mergeLinkList.merge(node, null);
//        Node n = mergeLinkList.merge(null, node2);
        Node n = mergeLinkList.merge(null, null);
        if(n != null){
            while(n.next != null){
                System.out.println(n.val);
                n = n.next;
            }
            System.out.println(n.val);
        }
    }
}

 

递归实现两个有序链表的合并