1234567891011121314151617181920212223242526272829303132333435363738 |
- import pytest
- # 链表
- class ListNode:
- def __init__(self, val=0, next=None):
- self.val = val
- self.next = next
- # 数组转链表
- def arr_to_linklist(arr):
- p = None
- for n in reversed(arr):
- node = ListNode(n)
- node.next = p
- p = node
- return p
- # 链表转数组
- def linkList_to_arr(head):
- res = []
- cur = head
- while cur is not None:
- res.append(cur.val)
- cur = cur.next
- return res
- # 数组转链表
- def list_to_linklist(arr):
- head = ListNode(arr[0])
- p = head
- for i in range(1, len(arr)):
- p.next = ListNode(arr[i])
- p = p.next
- return head
|