Given 2 Sorted LinkedList, merge them and return a new Sorted LinkedList.
Solution
This problem is a typical operation used in Merge Sort algorithm.
I. Python
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ n = ListNode(0) current = n while l1 and l2: if l1.val < l2.val: current.next = l1 l1 = l1.next else: current.next = l2 l2 = l2.next current = current.next while l1: current.next = l1 l1 = l1.next current = current.next while l2: current.next = l2 l2 = l2.next current = current.next return n.nextII. Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode n = new ListNode(0); ListNode current = n; while(l1 != null && l2 != null){ if (l1.val < l2.val){ current.next = l1; l1 = l1.next; }else{ current.next = l2; l2 = l2.next; } current = current.next; } while (l1 != null){ current.next = l1; l1 = l1.next; current = current.next; } while (l2 != null){ current.next = l2; l2 = l2.next; current = current.next; } return n.next; } }III. C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* n = new ListNode(0); ListNode* current = n; while (l1 != NULL && l2!= NULL){ if (l1->val < l2->val){ current->next = l1; l1 = l1->next; }else{ current->next = l2; l2 = l2->next; } current = current->next; } while(l1 != NULL){ current->next = l1; l1 = l1->next; current = current->next; } while(l2 != NULL){ current->next = l2; l2 = l2->next; current = current->next; } return n->next; } };IV. Javascript
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var mergeTwoLists = function(l1, l2) { var n = new ListNode(0); var current = n; while(l1 && l2){ if(l1.val < l2.val) { current.next = l1; l1 = l1.next; }else{ current.next = l2; l2 = l2.next; } current = current.next; } while(l1){ current.next = l1; l1 = l1.next; current = current.next; } while(l2){ current.next = l2; l2 = l2.next; current = current.next; } return n.next; };
No comments:
Post a Comment