GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — tech-code-interview/merge_two_sorted_lists.py at master · BarthJr/tech-code-interview Expand file tree/ Copy pathmerge_two_sorted_lists.pyMore file actions 57 lines (46 loc) · 1.37 KB / Copy pathmerge_two_sorted_lists.pyFile metadata and controls57 lines (46 loc) · 1.37 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 # https://leetcode.com/problems/merge-two-sorted-lists/ # 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. """ >>> l1 = create_linked_list([1, 2, 4]) >>> print_linked_list(l1) 1->2->4 >>> l2 = create_linked_list([1, 3, 4]) >>> print_linked_list(l2) 1->3->4 >>> merged_linked_lists = merge_two_lists(l1, l2) >>> print_linked_list(merged_linked_lists) 1->1->2->3->4->4 """ from typing import List # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def create_linked_list(lst: List) -> ListNode: if lst: head = tail = ListNode(lst[0]) for i in range(1, len(lst)): tail.next = ListNode(lst[i]) tail = tail.next return head def merge_two_lists(l1: ListNode, l2: ListNode) -> ListNode: head = tail = ListNode(0) while l1 and l2: if l1.val < l2.val: tail.next = l1 l1 = l1.next else: tail.next = l2 l2 = l2.next tail = tail.next tail.next = l1 or l2 return head.next def print_linked_list(linked_list): while linked_list: if linked_list.next: print(linked_list.val, end='->') else: print(linked_list.val) linked_list = linked_list.next |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |