栈
class Stack:
def __init__(self, limit: int 10):
self.stack = []
self.limit = limit
def __bool__(self):
return bool (self.stack)
def __str__(self):
return str(self.stack)
def push(self, data):
if len(self.stack) >= self.limit:
raise IndexError("out of limit)
self.stack.append(data)
def pop(self):
return self.stack.pop()
def peek(self):
return self.stack[-1]
def is_empty(self):
return not bool(self.stack)
def is_full(self):
return self.size() == self.limit
def size(self):
return len(size)
def __contains__(self, item):
return item in self.stack
链栈
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedStack:
def __init__(self):
self.top = None
def is_empty(self):
return self.top is None
def push(self, item):
new_data= Node(item)
if self.empty():
self.top = new_data
else:
new_data.next = self.top
self.top = new_data
def pop(self):
if self.is_empty():
raise IndexError("pop from empty stack")
else:
temp = self.top
self.top = temp.next
return temp.data