Listeler ve Sarmalayıcı Sınıflar (Wrapper Classes)
Python'da list veri yapısı zaten bir Stack'tir.
list.append(x)list.pop()💡 Not: Python list'leri dinamik boyutlu ve çok hızlıdır. Pratikte çoğu durumda direkt list kullanmak yeterlidir.
Daha temiz bir API için list'i bir sınıf içine sarabiliriz:
class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
print(f"-> Push: {item}")
def pop(self):
if self.is_empty():
return "Boş!"
item = self._items.pop()
print(f"<- Pop: {item}")
return item
def peek(self):
if self.is_empty():
return None
return self._items[-1]
def is_empty(self):
return len(self._items) == 0
# Test
s = Stack()
s.push("Kitap 1")
s.push("Kitap 2")
print(f"En üst: {s.peek()}")
s.pop()
s.pop()