s.next.value += 1 add_next = 0 else: s.next.value -= 9 add_next = 1 head1 = head1.next s = s.next while head2: s.next = head2 if add_next: if s.next.value + 1 < 10: s.next.value += 1 add_next = 0 else: s.next.value -= 9 add_next = 1 head2 = head2.next s = s.next if add_next: s.next = Node(1) printLinkedList(sumlist) if __name__ == '__main__': head1 = initiateLinkedList([7, 1, 9]) head2 = initiateLinkedList([5, 9, 2, 9]) printLinkedList(head1) print('second') printLinkedList(head2) sumLists(head1, head2)
def loop_detection(head): fast = slow = head while fast and fast.next: fast = fast.next.next slow = slow.next if fast is slow: break if fast is None or fast.next is None: return None slow = head while fast is not slow: fast = fast.next slow = slow.next return fast if __name__ == '__main__': head = initiateLinkedList( [10, 4, 7, 3, 8, 4, 3, 56, 8, 5, 2, 4, 6, 8, 4, 3]) temp = head for _ in range(10): temp = temp.next print(temp.value) last = head while last.next is not None: last = last.next last.next = temp print(loop_detection(head).value)
import sys sys.path.append('../../DataStructures/') from linkedList import Node, initiateLinkedList, printLinkedList, computeLength from KthToLast import KthToLast def palindrome(head): length = computeLength(head) for index in range(length // 2): temp = head for _ in range(index - 1): temp = temp.next kth = KthToLast(head, index) if temp.value != kth.value: return False return True if __name__ == '__main__': head = initiateLinkedList(['t', 'a', 'c', 'o', 'o', 'c', 'a', 't']) printLinkedList(head) print(palindrome(head))
return head1 else: return -1 def haveIntersection(head1, head2): last1 = head1 last2 = head2 while last1.next: last1 = last1.next while last2.next: last2 = last2.next return last1 is last2 if __name__ == '__main__': head1 = initiateLinkedList([10,4,7,3,8,4,3,56,8,5,2,4,6,8,4,3]) head2 = initiateLinkedList([3,11,5,7,8,5,3,2,4,5,7,8,5,]) temp1 = head1 temp2 = head2 for _ in range(7): temp1 = temp1.next for _ in range(4): temp2 = temp2.next temp1.next = temp2.next print('first') printLinkedList(head1) print('second') printLinkedList(head2) print('same') printLinkedList(intersection(head1, head2))