Problem Description: Merge sorted linked lists and return it as a new list. The new listshould is made by splicing together the nodes of the first of the lists.
Problem Analysis:
The algorithm itself is not difficult, comparing the values of two nodes of the linked list, whichever is smaller, assigns the result
The result of the method is to return the head pointer of the result linked list, so it should be saved with the pointer, and if set result is null, you will need to wait for L1 or L2 to result assignment to continue defining result.next, too cumbersome, so emulate the head node in C + + , define a new ListNode (0), then the head node is its Result.next;
Method Two is implemented by recursive method;
Code:
Class ListNode { int val; ListNode Next; ListNode (int x) {val = x;}} public class Solution {public ListNode mergetwolists (listnode L1, ListNode L2) {ListNode result = new ListNode (0); ListNode temp = Result;while ((L1! = null) && (L2! = null)) {if (L1.val <= l2.val) {temp.next = L1;L1 = L1.next;} else {temp.next = L2;L2 = L2.next;} temp = Temp.next;} if (L1! = null) Temp.next = L1;IF (L2! = null) Temp.next = L2; return result.next;} }
Method Two:
public class Solution {public ListNode mergetwolists (listnode L1, ListNode L2) { //Note The return value is not mistaken, this actually corresponds to the last related processing of the previous method if (L1 = = null) return L2; if (L2 = = null) return L1; ListNode result = null; if (l1.val <= l2.val) { result = L1; Result.next = mergetwolists (L1.next, L2); } else { result = L2;result.next = mergetwolists (L1, L2.next); } return result;} }
leetcode-21 Merge Sorted Lists