2022-12-23 00:44:40 +08:00
|
|
|
"""
|
2022-11-25 02:04:38 +08:00
|
|
|
File: linked_list.py
|
|
|
|
Created Time: 2021-12-11
|
|
|
|
Author: Krahets (krahets@163.com)
|
2022-12-23 00:44:40 +08:00
|
|
|
"""
|
2022-11-25 02:04:38 +08:00
|
|
|
|
2023-03-12 18:49:52 +08:00
|
|
|
class ListNode:
|
|
|
|
""" Definition for a singly-linked list node """
|
|
|
|
def __init__(self, val: int):
|
|
|
|
self.val: int = val # 结点值
|
2023-03-23 18:51:56 +08:00
|
|
|
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:
|
2023-03-12 18:49:52 +08:00
|
|
|
""" Generate a linked list with a list """
|
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-03-23 18:51:56 +08:00
|
|
|
def linked_list_to_list(head: ListNode | None) -> list[int]:
|
2023-03-12 18:49:52 +08:00
|
|
|
""" Serialize a linked list into an array """
|
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
|
|
|
|
|
2023-03-23 18:51:56 +08:00
|
|
|
def get_list_node(head: ListNode | None, val: int) -> ListNode | None:
|
2023-03-12 18:49:52 +08:00
|
|
|
""" Get a list node with specific value from a linked list """
|
2022-11-25 02:04:38 +08:00
|
|
|
while head and head.val != val:
|
|
|
|
head = head.next
|
|
|
|
return head
|