def test(self): head = Node(0) for i in range(1, 10): head.append_to_tail(i) head.print_all_data() self.assertEqual(find_kth_last_element2(3, head), 7) self.assertEqual(find_kth_last_element2(10, head), 0) self.assertEqual(find_kth_last_element2(12, head), None)
p1 = head p2 = head.get_next().get_next() if p2 == None: return while p2 != None and p2.get_next() != None: p2 = p2.get_next().get_next() p1 = p1.get_next() p1.set_next(p1.get_next().get_next()) return head ## given only access to that node. def delete_middle(node): # copy the next node to current position, then delete next node.set_data(node.get_next().get_data()) node.set_next(node.get_next().get_next()) # if 'node' is the last one, mark as dummy #--------------- head = Node(0) for i in range(1, 9): head.append_to_tail(i) head.print_all_data() print '----------------' delete_middle(head) head.print_all_data()