class TestLinkedList: new_list = LinkedList() def testNewLinkedList(self): self.new_list = LinkedList() assert self.new_list.head == None def testAddNode(self): self.new_list.addNode('node_1') assert self.new_list.head.data == 'node_1' def testGetLength(self): size = self.new_list.length() assert size == 1 self.new_list.addNode('node_2') size = self.new_list.length() assert size == 2 self.new_list.addNode('node_3') self.new_list.addNode('node_4') def testStr(self): print(self.new_list) def testDelOldestNode(self): node = self.new_list.delOldestNode() assert self.new_list.length() == 3 assert node == 'node_1' def testDelNewestNode(self): node = self.new_list.delNewestNode() assert self.new_list.length() == 2 assert node == 'node_4'
def clone(ll: LinkedList) -> LinkedList: clone_head = ll.head pos1 = ll.head pos2 = ll.head.next # duplicating all elements (by value in the linked list) # [a -> b -> c becomes a -> a -> b -> b -> c -> c] for _ in range(ll.length): pos1.next = Node(pos1.val) pos1 = pos1.next pos1.next = pos2 pos1 = pos1.next if pos2 is None: break pos2 = pos2.next # setting the clone head to the proper position clone_head = clone_head.next pos1 = ll.head # setting the random pointer of the cloned linked list # (every 2nd element in the new linked list: a -> [a] -> b -> [b] -> c -> [c]) for _ in range(ll.length - 1): pos1.next.random_ptr = pos1.random_ptr pos1 = pos1.next.next # reverting the linked list to its original form pos1 = ll.head pos2 = ll.head.next for _ in range(ll.length - 1): pos1.next = pos2.next pos2.next = pos2.next.next pos1 = pos1.next if pos2.next == None: break pos2 = pos2.next # creating the cloned linked list from the generated nodes cloned_LL = LinkedList() cloned_LL.head = clone_head cloned_LL.length = ll.length cloned_LL.rear = pos2 return cloned_LL
ll1 = LinkedList() ll1.add(5) ll1.add(6) ll1.add(7) ll1.add(8) ll2 = LinkedList() ll2.add(1) ll2.add(2) ll2.add(3) ll2.add(4) ll3 = LinkedList() ll3.add(9) ll3.rear.next = ll1.head.next.next ll3.rear = ll3.rear.next.next ll3.length = 3 print("Linked List 1:", ll1) print("Linked List 2:", ll2) print("Linked List 3:", ll3) print(common_node_pos(ll1, ll2)) print(common_node_pos(ll1, ll3).val) """ SPECS: TIME COMPLEXITY: O(n) SPACE COMPLEXITY: O(1) """