Welcome to Day 9. One more day to go and many more days to learn and improve!
Today was all about linked lists. A linked list is not like your regular list(array).
Simply put, a linked list consists of nodes where each node contains data and a pointer(link) to the next node in the list.
Unlike a regular list whose contents can be accessed by the index, contents of a linked list can only be accessed by traversing through the entire list till you get to the data you want.
If you've always wondered how Blockchain works, understanding linked lists will be a good start. And you can find a lot of resources on them online.
Now onto the task for today.
Instructions
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
TestCase
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
My Solution
My approach was to convert the linkedlist into a normal Python array(list), sort the array and then convert it back into a linkedlist to contain the values of the sorted list.
First, I created an empty array(list) to contain the values of the given linked list and an empty linked list to store the values from the array(list) using the ListNode(). Note, you can assign any value to the ListNode, however, be sure to assign the linked list to be returned to this new linked list else it return an empty linked list.
Then, i used a for loop to traverse the given linkedlist(as long as it's not empty) and appended each value from the linked list into the array. I used the sorted() method to sort this new list and then used a for loop to iterate through each value in each the newlist and stored in the linked lsit created, linking each value to the next.
Finally, i returned the new linked list now filled with the contents of the sorted array.
You can view my submission below.
Onwards to the final stretch!