Last active
October 18, 2021 18:39
-
-
Save gladimdim/3b6598c97a2f9ef2fd70139ddf96adf4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node<T> { | |
T value; | |
Node<T>? next; | |
Node(this.value, [this.next]); | |
} | |
/// Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. | |
/// https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists/ | |
Node? mergeTwoLists(Node? l1, Node? l2) { | |
if (l1 == null && l2 == null) { | |
return null; | |
} | |
List data = []; | |
// extract all data from linked list nodes into arrays | |
while (l1 != null) { | |
data.add(l1.value); | |
l1 = l1.next; | |
} | |
while (l2 != null) { | |
data.add(l2.value); | |
l2 = l2.next; | |
} | |
data.sort(); | |
Node? tmp; | |
Node? current; | |
// convert sorted array into Linked List | |
// this will be our final result | |
for (var val in data) { | |
// handle first case when new LinkedList was not yet created | |
if (tmp == null) { | |
tmp = Node(val); | |
current = tmp; | |
continue; | |
} | |
current!.next = Node(val); | |
current = current.next!; | |
} | |
return tmp; | |
} | |
void main() { | |
var f1 = Node<int>(1, Node(7, Node(10))); | |
var f2 = Node<int>(-3, Node(4, Node(5))); | |
print("Merging two lists"); | |
var result = mergeTwoLists(f1, f2); | |
print(result!.value); | |
print(result!.next!.value); | |
print(result!.next!.next!.value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment