【算法】java递归方法合并两个有序链表

链表的特点想必不用我说了,一个node有属性data,next。多了不说,直接上代码!

节点类:

package com.stury.leetcode.node;

/**
 *  * @auther: david
 *  * @date: 2020/03/25 15
 *  * @Description: 结点信息
 *  
 */
public class Node {
    // 节点数据
    public int data;

    // 直向下一节点
    public Node next;

    // 构造函数,赋值data
    public Node(int data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return this.data + "";
    }

}

测试类:

package com.stury.leetcode.node;

/**
 *  * @auther: david
 *  * @date: 2020/03/25 15
 *  * @Description: 两个有序单链表合并
 *  
 */
public class MyTest {

    public static Node Merge(Node list1, Node list2) {
        if (list1 == null)
            return list2;
        if (list2 == null)
            return list1;
        if (list1.data <= list2.data) {
            list1.next = Merge(list1.next, list2);
            return list1;
        } else {
            list2.next = Merge(list1, list2.next);
            return list2;
        }
    }

    /**
     * 打印链表
     * @param head
     */
    public static void print(Node head){
        Node temp = head;
        while (temp != null){
            System.out.println(temp);
            temp = temp.next;
        }
    }

    public static void main(String[] args) {
        Node node1 = new Node(2);
        Node node3 = new Node(3);
        node1.next = node3;


        Node node2 = new Node(1);
        Node node4 = new Node(4);
        Node node5 = new Node(5);

        node2.next = node4;
        node4.next = node5;

        System.out.println("单链表1");
        print(node1);
        System.out.println("单链表2");
        print(node2);

        System.out.println("合并后的链表:");
        print(Merge(node1, node2));

    }
}

结果输出:

单链表1
2
3
单链表2
1
4
5
合并后的链表:
1
2
3
4
5

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章