剑指OFFER笔记_25_合并两个排序的链表_JAVA实现
题目:合并两个排序的链表
- 输入两个递增排序的链表,合并这两个链表并使新链表中的节点依然是递增排序的。
解题思路
- 此题可以采用递归的方法。
- 首先确定新链表的头节点。将两个链表的头节点值进行比较即可得到。
- 然后确认新链表的头节点的next,此时可以递归调用自身这个函数,将形参进行变化,以获得除去被使用的头节点的两个链表合成之后的头节点,将它作为next即可。
- 当两个链表有一个为空的时候,让结果等于另一个链表即可。即使出现两个链表都为空的情况,也能返回一个null,这也是正确的处理。
代码
ListNode结构代码
package q25;
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) {
this.val = x;
this.next = null;
}
public static ListNode createLink(int[] arr)
{
if (arr == null || arr.length == 0)
{
return null;
}
ListNode head = new ListNode(arr[0]);
ListNode pNode = head;
for (int i = 1; i < arr.length; i++)
{
ListNode temp = new ListNode(arr[i]);
pNode.next = temp;
pNode = pNode.next;
}
return head;
}
public static void outputLink(ListNode head)
{
ListNode pNode = head;
while (pNode != null)
{
System.out.print(pNode.val + " ");
pNode = pNode.next;
}
System.out.println();
}
}
函数主体部分代码
package q25;
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}else 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;
}
}
测试部分代码
package q25;
public class TestApp {
public static void main(String[] args) {
Solution s = new Solution();
//正常输入情况
int[] array1 = {1,3,5,7,9};
int[] array2 = {2,4,6,8,10};
ListNode l1 = ListNode.createLink(array1);
ListNode l2 = ListNode.createLink(array2);
ListNode head = s.mergeTwoLists(l1, l2);
ListNode.outputLink(head);
//l1为空
int[] array3 = {};
int[] array4 = {1,2,3,4,5};
l1 = ListNode.createLink(array3);
l2 = ListNode.createLink(array4);
head = s.mergeTwoLists(l1, l2);
ListNode.outputLink(head);
//l2为空
int[] array5 = {1,2,3,4,5};
int[] array6 = {};
l1 = ListNode.createLink(array5);
l2 = ListNode.createLink(array6);
head = s.mergeTwoLists(l1, l2);
ListNode.outputLink(head);
//l1 l2都为空
int[] array7 = {};
int[] array8 = {};
l1 = ListNode.createLink(array7);
l2 = ListNode.createLink(array8);
head = s.mergeTwoLists(l1, l2);
ListNode.outputLink(head);
}
}
运行结果截图
LeetCode运行截图