|
| 1 | +import unittest |
| 2 | + |
| 3 | +from problems.linked_list.reorder_list import ReorderList |
| 4 | +from problems.util.list_node import ListNode |
| 5 | + |
| 6 | + |
| 7 | +def build_list(values): |
| 8 | + if not values: |
| 9 | + return None |
| 10 | + head = ListNode(values[0]) |
| 11 | + current = head |
| 12 | + for value in values[1:]: |
| 13 | + current.next = ListNode(value) |
| 14 | + current = current.next |
| 15 | + return head |
| 16 | + |
| 17 | + |
| 18 | +def list_to_array(head): |
| 19 | + result = [] |
| 20 | + current = head |
| 21 | + while current: |
| 22 | + result.append(current.val) |
| 23 | + current = current.next |
| 24 | + return result |
| 25 | + |
| 26 | + |
| 27 | +class ReorderListTest(unittest.TestCase): |
| 28 | + def setUp(self): |
| 29 | + self.reorder_list = ReorderList() |
| 30 | + |
| 31 | + def test_empty_list(self): |
| 32 | + head = None |
| 33 | + self.reorder_list.reorderList(head) |
| 34 | + self.assertIsNone(head) |
| 35 | + |
| 36 | + def test_single_element_list(self): |
| 37 | + head = build_list([1]) |
| 38 | + self.reorder_list.reorderList(head) |
| 39 | + self.assertEqual(list_to_array(head), [1]) |
| 40 | + |
| 41 | + def test_two_element_list(self): |
| 42 | + head = build_list([1, 2]) |
| 43 | + self.reorder_list.reorderList(head) |
| 44 | + self.assertEqual(list_to_array(head), [1, 2]) |
| 45 | + |
| 46 | + def test_three_element_list(self): |
| 47 | + head = build_list([1, 2, 3]) |
| 48 | + self.reorder_list.reorderList(head) |
| 49 | + self.assertEqual(list_to_array(head), [1, 3, 2]) |
| 50 | + |
| 51 | + def test_four_element_list(self): |
| 52 | + head = build_list([1, 2, 3, 4]) |
| 53 | + self.reorder_list.reorderList(head) |
| 54 | + self.assertEqual(list_to_array(head), [1, 4, 2, 3]) |
| 55 | + |
| 56 | + def test_odd_number_of_elements(self): |
| 57 | + head = build_list([1, 2, 3, 4, 5]) |
| 58 | + self.reorder_list.reorderList(head) |
| 59 | + self.assertEqual(list_to_array(head), [1, 5, 2, 4, 3]) |
| 60 | + |
| 61 | + def test_even_number_of_elements(self): |
| 62 | + head = build_list([1, 2, 3, 4, 5, 6]) |
| 63 | + self.reorder_list.reorderList(head) |
| 64 | + self.assertEqual(list_to_array(head), [1, 6, 2, 5, 3, 4]) |
| 65 | + |
| 66 | + def test_get_middle(self): |
| 67 | + head = build_list([1, 2, 3, 4, 5]) |
| 68 | + middle = self.reorder_list.get_middle(head) |
| 69 | + self.assertEqual(middle.val, 3) |
| 70 | + |
| 71 | + def test_reverse_list(self): |
| 72 | + head = build_list([1, 2, 3, 4, 5]) |
| 73 | + reversed_head = self.reorder_list.reverse(head) |
| 74 | + self.assertEqual(list_to_array(reversed_head), [5, 4, 3, 2, 1]) |
| 75 | + |
| 76 | + |
| 77 | +if __name__ == '__main__': |
| 78 | + unittest.main() |
0 commit comments