题目:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路:
递归当前较小节点的下一个结点
代码:
package 合并两个排序的链表;
class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
/**
* 链表的长度
*
* @param head
* @return
*/
public int length(ListNode head) {
ListNode curNode = head;
int length = 0;
while (curNode != null) {
curNode = curNode.next;
length++;
}
return length;
}
/**
* 输出链表
*
* @param head
*/
public void printList(ListNode head) {
ListNode curNode = head;
// 循环遍历到尾节点
while (curNode != null) {
System.out.print(curNode.val + " ");
curNode = curNode.next;
}
System.out.println();
}
}
class Solution {
/**
* 递归方式
* @param list1
* @param list2
* @return
*/
public ListNode Merge(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
/**
* 简洁写法,需理解一番
*/
// if (list1.val <= list2.val) {
// list1.next = Merge(list1.next, list2);
// return list1;
// } else {
// list2.next = Merge(list1, list2.next);
// return list2;
// }
ListNode newHead = null;
if (list1.val <= list2.val) {
newHead = list1;
newHead.next = Merge(list1.next, list2);
} else {
newHead = list2;
newHead.next = Merge(list1, list2.next);
}
return newHead;
}
/**
* 非递归方式
* @param list1
* @param list2
* @return
*/
// public ListNode Merge(ListNode list1, ListNode list2) {
// if (list1 == null) { // 输入为空判断
// return list2;
// }
// if (list2 == null) {
// return list1;
// }
//
// ListNode mergeHead = null; // 创建合并后的链表
// ListNode current = null; // 创建当前链表
// while (list1 != null && list2 != null) { // 两个链表都不为空时合并
// if (list1.val <= list2.val) {
// if (mergeHead == null) { // 为新链表、当前链表赋予 list1、list2 中头结点较小的链表值
// mergeHead = current = list1;
// } else {
// current.next = list1;
// current = current.next;
// }
// list1 = list1.next; // list1 的当前节点被合并后,向后移动一个节点,
// } else {
// if (mergeHead == null) { // 为新链表表头节点、当前节点赋予【当前】最小值
// mergeHead = current = list2;
// } else {
// current.next = list2; // 当前节点有初始值时,赋予 next 节点值
// current = current.next; // 当前节点向后移动一个节点
// }
// list2 = list2.next; // list2 的当前节点被合并后,向后移动一个节点,
// }
// }
// if (list1 == null) {
// current.next = list2;
// } else {
// current.next = list1;
// }
// return mergeHead;
// }
}
public class Demo {
public static void main(String[] args) {
ListNode listNode = new ListNode(1);
listNode.next = new ListNode(4);
listNode.next.next = new ListNode(5);
listNode.next.next.next = new ListNode(8);
listNode.next.next.next.next = new ListNode(9);
listNode.next.next.next.next.next = new ListNode(10);
ListNode listNode2 = new ListNode(2);
listNode2.next = new ListNode(3);
listNode2.next.next = new ListNode(6);
listNode2.next.next.next = new ListNode(7);
Solution solution = new Solution();
ListNode merge = solution.Merge(listNode, listNode2);
merge.printList(merge);
}
}