class Node {
Node next = null;//下一个结点
int data;//结点数据
public Node(int data) {
this.data = data;
}
@Override
public String toString() {
return "Node{" +
"data=" + data +
'}';
}
}
/**
* 合并两个有序链表
* @param head1
* @param head2
* @return
*/
public static Node mergeLinkedList(Node head1, Node head2) {
if (head1 == null) return head2;
if (head2 == null) return head1;
Node head = new Node(-1);
Node res = head;
Node cur1 = head1;
Node cur2 = head2;
while (cur1 != null && cur2 != null){
if (cur1.data <= cur2.data){
res.next = cur1;
cur1 = cur1.next;
}else{
res.next = cur2;
cur2 = cur2.next;
}
res = res.next;
}
if (cur1 != null){
res.next = cur1;
}
if (cur2 != null){
res.next = cur2;
}
return head.next;
}