2022-12-23 00:44:40 +08:00
|
|
|
"""
|
2023-07-19 16:09:27 +08:00
|
|
|
File: list_node.py
|
2022-11-25 02:04:38 +08:00
|
|
|
Created Time: 2021-12-11
|
2024-02-07 22:21:18 +08:00
|
|
|
Author: krahets (krahets@163.com)
|
2022-12-23 00:44:40 +08:00
|
|
|
"""
|
2022-11-25 02:04:38 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
|
2023-03-12 18:49:52 +08:00
|
|
|
class ListNode:
|
2024-01-07 04:04:01 +08:00
|
|
|
"""链表节点类"""
|
2023-04-09 05:05:35 +08:00
|
|
|
|
2023-03-12 18:49:52 +08:00
|
|
|
def __init__(self, val: int):
|
2023-04-09 05:05:35 +08:00
|
|
|
self.val: int = val # 节点值
|
|
|
|
self.next: ListNode | None = None # 后继节点引用
|
|
|
|
|
2022-11-25 02:04:38 +08:00
|
|
|
|
2023-03-23 18:51:56 +08:00
|
|
|
def list_to_linked_list(arr: list[int]) -> ListNode | None:
|
2024-03-31 03:06:41 +08:00
|
|
|
"""将列表反序列化为链表"""
|
2022-11-25 02:04:38 +08:00
|
|
|
dum = head = ListNode(0)
|
|
|
|
for a in arr:
|
|
|
|
node = ListNode(a)
|
|
|
|
head.next = node
|
|
|
|
head = head.next
|
|
|
|
return dum.next
|
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
|
2023-03-23 18:51:56 +08:00
|
|
|
def linked_list_to_list(head: ListNode | None) -> list[int]:
|
2024-03-31 03:06:41 +08:00
|
|
|
"""将链表序列化为列表"""
|
2023-03-23 18:51:56 +08:00
|
|
|
arr: list[int] = []
|
2022-11-25 02:04:38 +08:00
|
|
|
while head:
|
|
|
|
arr.append(head.val)
|
|
|
|
head = head.next
|
|
|
|
return arr
|