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;
Subscribe to:
Post Comments (Atom)
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 ...
-
Source Link: https://app.codility.com/programmers/lessons/15-caterpillar_method/count_distinct_slices/ Question: An integer M and a...
-
Source Link: https://app.codility.com/programmers/lessons/15-caterpillar_method/count_triangles/ Question: A zero-indexed array A consi...
-
Source Link: https://codility.com/programmers/lessons/9-maximum_slice_problem/max_slice_sum/ Question: A non-empty zero-indexed array A...
No comments:
Post a Comment