utils.py 655 B

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