Sunday, August 20, 2017

LeetCode - 21. Merge Two Sorted Lists

Source Link:
https://leetcode.com/problems/merge-two-sorted-lists/description/ 

Question:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

My Solution: Note:
1. we create a "dummy node" to be the "previous node" of the head of the new list to avoid some potential bugs (and to keep the 1st node)
2. process the nodes of both lists (until one node becomes "null")
while(a != null && b != null)
3. case 1: a is smaller than b
if(a.val <= b.val){
current.next = a;
a = a.next;
current = current.next;
}

4. case 2: b is smaller than a
else{
current.next = b;
b = b.next;
current = current.next;
}

5. the remaining nodes
if(a == null){
current.next = b;
}
if(b == null){
current.next = a;
}

6. dummy.next is the "1st" node
return dummy.next;

No comments:

Post a Comment

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...