pygorithm/link_list/singly_link.py

50 lines
1.0 KiB
Python

from typing import Self
class SinglyNode:
def __init__(self, value, nex: Self | None):
self.value = value
self.next = nex
def __repr__(self):
return f'Node({self.value})'
class SinglyLinkList:
__string = ''
def __init__(self):
self.size = 0
self.head: SinglyNode | None = None
def __repr__(self):
return self.__string
def is_empty(self) -> bool:
return self.size == 0
# 新节点总是添加到头部
def push(self, value):
if self.head is None:
self.__string = f'{value} -> None'
else:
self.__string = f'{value} -> ' + self.__string
node = SinglyNode(value, self.head)
self.head = node
self.size += 1
def pop(self) -> SinglyNode:
head = self.head
node = self.head.next
self.head = node
return head
def peek(self):
return self.head.value
def iter(self):
cur = self.head
while cur:
yield cur.value
cur = cur.next