题目:输入两个递增排序的链表,合并这两个链表并使新链表中的节点依然时递增排序的。例如:输入如图所示的链表1和链表2,则合并之后的升序链表如图3所示。链表的定义如下:
class ListNode{
int value;
ListNode next;
ListNode(int value){
this.value = value;
}
}
直接上代码:
public class sortArrayByOddEven {
public static void main(String[] args) {
ListNode pHead = new ListNode(1);
ListNode pAhead = new ListNode(3);
ListNode pBhead = new ListNode(5);
ListNode pChead = new ListNode(7);
pHead.next = pAhead;
pAhead.next = pBhead;
pBhead.next = pChead;
ListNode p1Head = new ListNode(2);
ListNode p2head = new ListNode(4);
ListNode p3head = new ListNode(6);
ListNode p4head = new ListNode(8);
p1Head.next = p2head;
p2head.next = p3head;
p3head.next = p4head;
p1Head = linkNode(pHead,p1Head);
while (p1Head != null) {
System.out.print(p1Head.value + ",");
p1Head = p1Head.next;
}
}
private static ListNode linkNode(ListNode pAhead, ListNode pBhead) {
if (pAhead == null && pBhead == null) //当两个头节点都为空的时候,我们直接返回null
return null;
if (pAhead == null) {
return pBhead;
} else if (pBhead == null) {
return pAhead;
}
ListNode returnNode = null; //定义一个返回的ListNode;
if(pAhead.value<pBhead.value) { //进行判断pAhead和pBhead的大小,然后利用递归赋值return.next
returnNode = pAhead;
returnNode.next = linkNode(pAhead.next, pBhead);
}else {
returnNode = pBhead;
returnNode.next = linkNode(pAhead, pBhead.next);
}
return returnNode;
}
分析:
在第一次书写代码的过程中,我们发现里面存在递归。因此我们开始改造代码:
1)书写递归的约束条件:
if (pAhead == null && pBhead == null) //当两个头节点都为空的时候,我们直接返回null
return null;
if (pAhead == null) {
return pBhead;
} else if (pBhead == null) {
return pAhead;
}
2)使用递归来帮助我们完成returnNode.next 以及return.next.next后面的操作;
在以后的递归中,创建的ListNode returnNode 都是作为一个新的节点进行链接。