# 【算法】java遞歸方法合併兩個有序鏈表

``````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;
}
}

/**
* 打印鏈表
*/
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

1
4
5

1
2
3
4
5``````