def add_two_nums(l1, l2): result = list.Linked_List() head1 = l1.root head2 = l2.root carry_dataue = 0 while head1 and head2: sum_data = head1.data + head2.data + carry_dataue if sum_data >= 10: result.add((sum_data) % 10) carry_dataue = sum_data / 10 else: result.add(sum_data) head1 = head1.next head2 = head2.next return result
def merge_sorted_lists(l1, l2): root1 = l1.root root2 = l2.root new_list = list.Linked_List() if (not root1 or not root2): return None # iterate over lists while root1 and root2: if root1.data < root2.data: new_list.add(root1.data) root1 = root1.next else: new_list.add(root2.data) root2 = root2.next # add remaining elements onto new list (if any) if (not root1 and not root2): return new_list else: if root1: helper_add(root1, new_list) else: helper_add(root2, new_list) return new_list
new_list.add(root1.data) root1 = root1.next else: new_list.add(root2.data) root2 = root2.next # add remaining elements onto new list (if any) if (not root1 and not root2): return new_list else: if root1: helper_add(root1, new_list) else: helper_add(root2, new_list) return new_list def helper_add(root, list): while (root): list.add(root.data) root = root.next return list l1 = list.Linked_List() l2 = list.Linked_List() for i in range(1, 6, 2): # 1,3,5 l1.add(i) for i in range(2, 7, 2): # 2,4,6 l2.add(i)
import list def rotate_list(list,k): root = list.root if(not root): return None fast = list.root slow = list.root # fast should start at list length - k for i in range(0,k): fast = fast.next # the new tail is at list length - k while (fast.next): fast = fast.next slow = slow.next # new head is slow.next value new_head = slow.next # new tail is slow.next slow.next = None # fast.next now points to old head fast.next = root # set new head list.root = new_head return list l = list.Linked_List() for i in range(1,6): l.add(i) l.remove(2) l.print_list() def run(): rotate_list(l,2).print_list() # 4 5 1 2 3