题目:输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
递归的思想
public static ListNode merge(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
ListNode head = null;
if (list1.getnValue() < list2.getnValue()) {
head = list1;
head.setpNext(merge(list1.getpNext(), list2));
} else {
head = list2;
head.setpNext(merge(list1, list2.getpNext()));
}
return head;
}
public class ListNode {
private int nValue;
private ListNode pNext;
public int getnValue() {
return nValue;
}
public void setnValue(int nValue) {
this.nValue = nValue;
}
public ListNode getpNext() {
return pNext;
}
public void setpNext(ListNode pNext) {
this.pNext = pNext;
}
public static ListNode createList(int[] arr) {
if (arr.length == 0) {
return null;
}
ListNode head = new ListNode();
ListNode currentNode = head;
for (int i = 0; i < arr.length-1; i++) {
currentNode.nValue = arr[i];
currentNode.pNext = new ListNode();
currentNode = currentNode.pNext;
}
currentNode.nValue = arr[arr.length-1];
currentNode.pNext = null;
return head;
}
public static void printList(ListNode listNode) {
StringBuffer buf = new StringBuffer("[");
ListNode currentNode = listNode;
while (currentNode != null) {
buf.append(currentNode.nValue).append(",");
currentNode = currentNode.getpNext();
}
String result = buf.length() == 1?buf.toString():buf.substring(0, buf.length()-1);
System.out.println(result+"]");
}
}