Last active
May 12, 2025 02:17
-
-
Save jac18281828/10ca6e80547b19ea5d4c755afb0e2cd6 to your computer and use it in GitHub Desktop.
Hackerrank Merged two sorted linked lists
This file contains hidden or 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
| import sys | |
| class SinglyLinkedListNode: | |
| def __init__(self, node_data): | |
| self.data = node_data | |
| self.next = None | |
| class SinglyLinkedList: | |
| def __init__(self): | |
| self.head = None | |
| self.tail = None | |
| def insert_node(self, node_data): | |
| node = SinglyLinkedListNode(node_data) | |
| if not self.head: | |
| self.head = node | |
| else: | |
| self.tail.next = node | |
| self.tail = node | |
| def print_singly_linked_list(node, sep, fptr): | |
| while node: | |
| fptr.write(str(node.data)) | |
| node = node.next | |
| if node: | |
| fptr.write(sep) | |
| def merge_lists(head1, head2): | |
| root = SinglyLinkedList() | |
| while head1 and head2: | |
| if head1.data <= head2.data: | |
| root.insert_node(head1.data) | |
| head1 = head1.next | |
| else: | |
| root.insert_node(head2.data) | |
| head2 = head2.next | |
| while head1: | |
| root.insert_node(head1.data) | |
| head1 = head1.next | |
| while head2: | |
| root.insert_node(head2.data) | |
| head2 = head2.next | |
| return root.head | |
| if __name__ == "__main__": | |
| l1 = [1, 4, 7, 8, 900] | |
| l2 = [2, 8, 9, 11, 100] | |
| list1 = SinglyLinkedList() | |
| for i in l1: | |
| list1.insert_node(i) | |
| list2 = SinglyLinkedList() | |
| for j in l2: | |
| list2.insert_node(j) | |
| merged_list = merge_lists(list1.head, list2.head) | |
| print_singly_linked_list(merged_list, " ", sys.stdout) | |
| print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment