List: merge two ordered lists

 

Title Description

Two monotonically increasing input list and output list after synthesis of two lists, of course, after that we need to meet synthesis list - decreasing the rules.

Problem-solving ideas

Two solutions: recursive and non-recursive

This topic is in the merge sort merge operation, the two ordered arrays (list) into an ordered array.

Non-recursive:

The first while loop, to compare the l1 and l2, who will come to merge small to listNode, until l1 or l2 is empty

The second and third while loop while loop, l1 or l2 to merge into the remaining node listNode

Finally, it returns firstNode.next // head node is not needed

Reference Code

Recursive: Running time: 27ms take up memory: 9564k

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode Merge(ListNode list1,ListNode list2) {
12         if(list1 == null) {
13             return list2;
14         }
15         if(list2 == null) {
16             return list1;
17         }
18         ListNode head = null;
19         if(list1.val < list2.val) {
20             head = list1;
21             head.next = Merge(list1.next, list2);
22         } else {
23             head = list2;
24             head.next = Merge(list1, list2.next);
25         }
26         return head;
27     }
28 }

Non-recursive: Running time: 26ms take up memory: 9544k

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode Merge(ListNode l1, ListNode l2) {
12         ListNode listNode = new ListNode(0);
13         ListNode firstNode = listNode;
14         while (l1 != null && l2 != null) {  // compared to l1 and l2, who will come to be incorporated into small listnode, l1 or l2 is empty until the
 15              IF (l1.val <= l2.val) {
 16                  listNode.next = l1;
 . 17                  l1 = l1. Next;
 18 is              } the else {
 . 19                  listNode.next = l2;
 20 is                  l2 = l2.next;
 21 is              }
 22 is              listnode = listNode.next;
 23 is          }
 24          the while (! L1 = null ) {        // l2 If empty, the rest will be the l1 added to listNode in
 25             = listNode.next l1;
 26 is              l1 = l1.next;
 27              listnode = listNode.next;
 28          }
 29          the while (! l2 = null ) {        // If empty l1, l2 remaining will be added to the listnode
 30              listnode. = Next L2;
 31 is              L2 = l2.next;
 32              listnode = listNode.next;
 33 is          }
 34 is          return firstNode.next;
 35      }
 36 }

 

Guess you like

Origin www.cnblogs.com/carry6/p/11520868.html