问题描述: 输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。
/*
* 问题描述:
* 输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。
*/
//定义链表结点的结构
class ListNode {
ListNode next;
int data;
public ListNode() {
}
public ListNode(int data) {
this.data = data;
}
}
public class MergeList {
public static ListNode Merge(ListNode head1, ListNode head2) {
if (head1 == null) {
return head2;
}
if (head2 == null) {
return head1;
}
ListNode mergeNode = null;
;
if (head1.data < head2.data) {
mergeNode = head1;
mergeNode.next = Merge(head1.next, head2);
} else {
mergeNode = head2;
mergeNode.next = Merge(head1, head2.next);
}
return mergeNode;
}
public static void printList(ListNode merge) {
ListNode head = merge;
while (head != null) {
System.out.print(head.data);
head = head.next;
}
System.out.println();
}
}