مثال حلشده
متوسط لیست پیوندی
صورت مسئله
سه عدد ۱۰، ۲۰، ۳۰ را اضافه کن، ۲۰ را پیدا کن، و بگو دسترسی به عنصر iام چه هزینهای دارد.
راهحل گامبهگام
۴ گام باقی مانده
class Node:
def __init__(self, value, nxt=None):
self.value = value
self.next = nxt
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.head is None:
self.head = Node(value)
return
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(value)
def find(self, value):
cur = self.head
while cur is not None:
if cur.value == value:
return cur
cur = cur.next
return None
ll = LinkedList()
for v in (10, 20, 30):
ll.append(v)
print(ll.find(20).value) # 20
print(ll.find(99)) # None