【算法】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

 

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