LeetCode第21题,合并两个有序链表.java
由于已经有序了,相似归并排序中的合并同样,操做不难,直接上代码了.git
ListNode t = new ListNode(0); ListNode head = t; while(l1 != null && l2 != null) { if(l1.val < l2.val) { t.next = l1; l1 = l1.next; } else { t.next = l2; l2 = l2.next; } t = t.next; } while(l1 != null) { t.next = l1; l1 = l1.next; t = t.next; } while(l2 != null) { t.next = l2; l2 = l2.next; t = t.next; } return head.next;
这个能够采用递归优化,并且不用额外设置一个移动的临时结点t.首先对两个指针进行判空操做,其中一个为空的话返回另外一个,而后进行递归合并,首先建立一个head结点,进行赋值后递归合并next结点,将返回值赋给head.next,最后返回head.github
if(l1 == null) return l2; if(l2 == null) return l1; ListNode head = null; if(l1.val < l2.val) { head = l1; head.next = mergeTwoLists(l1.next, l2); } else { head = l2; head.next = mergeTwoLists(l1, l2.next); } return head;
github优化
码云spa