题目:输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。
——来源于《剑指offer》
- 循环实现
package com.qianyu.jianzhioffer.connectTwoLinklists;
/**
* @author lijing
* @date 2019-07-29-10:04
* @discription 合并两个有序链表
*/
public class Solution {
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public ListNode Merge(ListNode list1, ListNode list2) {
// 非空校验
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
ListNode p1 = list1;
ListNode p2 = list2;
// front指向合并后链表的前一个结点
ListNode front = null;
while (p1 != null && p2 != null) {
// 在p1中找到比p2大的结点,在此节点之前插入
if (p2.val < p1.val) {
ListNode temp = p2;
p2 = temp.next;
temp.next = p1;
front.next = temp;
}
front = p1;
p1 = p1.next;
}
// 如果p2没有遍历完,就将p2追加到p1的尾部
if (p2 != null) {
front.next = p2;
}
return list1;
}
}
- 递归实现
public ListNode Merge2(ListNode list1, ListNode list2) {
// 非空校验
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
ListNode head = null;
if (list1.val < list2.val) {
head = list1;
head.next = Merge2(list1.next, list2);
} else {
head = list2;
head.next = Merge2(list1, list2.next);
}
return head;
}