题目描述

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

分析

1、遍历两个链表,按大小顺序拼接。

  1. public class Solution {
  2. public ListNode Merge(ListNode list1, ListNode list2) {
  3. ListNode head = new ListNode(0);
  4. ListNode movnode = head;
  5. while (list1 != null && list2 != null) {
  6. if (list1.val > list2.val) {
  7. movnode.next = list2;
  8. list2 = list2.next;
  9. } else {
  10. movnode.next = list1;
  11. list1 = list1.next;
  12. }
  13. movnode = movnode.next;
  14. }
  15. if (list1 != null) {
  16. movnode.next = list1;
  17. }
  18. if (list2 != null) {
  19. movnode.next = list2;
  20. }
  21. return head.next;
  22. }
  23. }

2、递归

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