utils.py 882 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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
  31. # 计算链表长度
  32. def len_of_linklist(head):
  33. lens = 0
  34. p = head
  35. while p:
  36. lens += 1
  37. p = p.next
  38. return lens
  39. def deleteNode(node):
  40. node.val = node.next.val
  41. node.next = node.next.next