输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则;

分析

  1. 先判断输入的链表是否为空的指针。如果第一个链表为空,则直接返回第二个链表;如果第二个链表为空,则直接返回第一个链表。如果两个链表都是空链表,合并的结果是得到一个空链表。
  2. 两个链表都是排序好的,我们只需要从头遍历链表,判断当前指针,哪个链表中的值小,即赋给合并链表指针即可

代码

递归版本

  1. public class Solution {
  2. //1->3
  3. //2
  4. public ListNode Merge(ListNode list1, ListNode list2) {
  5. if (list1 == null) {
  6. return list2;
  7. }
  8. if (list2 == null) {
  9. return list1;
  10. }
  11. if (list1.val <= list2.val) {
  12. list1.next = Merge(list1.next, list2);
  13. return list1;
  14. } else {
  15. list2.next = Merge(list1, list2.next);
  16. return list2;
  17. }
  18. }
  19. }

非递归版本

  1. public ListNode Merge(ListNode list1, ListNode list2) {
  2. if (list1 == null) {
  3. return list1;
  4. }
  5. if (list2 == null) {
  6. return list2;
  7. }
  8. ListNode res = new ListNode(-1);
  9. ListNode tempNode = res;
  10. while (list1 != null && list2 != null) {
  11. if (list1.val < list2.val) {
  12. tempNode.next = list1;
  13. list1 = list1.next;
  14. } else {
  15. tempNode.next = list2;
  16. list2 = list2.next;
  17. }
  18. tempNode = tempNode.next;
  19. }
  20. while (list1 != null) {
  21. tempNode.next = list1;
  22. list1 = list1.next;
  23. tempNode = tempNode.next;
  24. }
  25. while (list2 != null) {
  26. tempNode.next = list2;
  27. list2 = list2.next;
  28. tempNode = tempNode.next;
  29. }
  30. return res.next;
  31. }