utils.py 738 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import pytest
  2. def arr_to_linklist(arr):
  3. p = None
  4. for n in reversed(arr):
  5. node = ListNode(n)
  6. node.next = p
  7. p = node
  8. return p
  9. def linkList_to_arr(head):
  10. res = []
  11. cur = head
  12. while cur is not None:
  13. res.append(cur.val)
  14. cur = cur.next
  15. return res
  16. def list_to_linklist(arr):
  17. head = ListNode(arr[0])
  18. p = head
  19. for i in range(1, len(arr)):
  20. p.next = ListNode(arr[i])
  21. p = p.next
  22. return head
  23. class ListNode:
  24. def __init__(self, val=0, next=None):
  25. self.val = val
  26. self.next = next
  27. def test_arr_to_linklist():
  28. arr = [1, 3, 4, 5, 6]
  29. head = arr_to_linklist(arr)
  30. arr1 = linkList_to_arr(head)
  31. assert arr == arr1