由于 Python 基础数据类型封装得比较强大,实现栈和队列显得很容易
- Python 实现栈
class Stack(object):
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
self.items.pop()
def peek(self):
"""返回栈顶元素"""
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
if __name__ == '__main__':
stack = Stack()
print('栈是否为空:', stack.is_empty())
stack.push(4)
stack.push(8)
stack.push(1)
print(stack.peek())
stack.pop()
print('栈是否为空:', stack.is_empty())
print(stack.size())
- Python 实现队列
class Queue(object):
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
self.items.pop()
def size(self):
return len(self.items)
if __name__ == '__main__':
queue = Queue()
print('队列是否为空:', queue.is_empty())
queue.enqueue(10)
queue.enqueue(8)
queue.enqueue(4)
queue.dequeue()
print(queue.size())
- Python 实现双端队列
class Deque(object):
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def add_front(self, item):
self.items.insert(0, item)
def add_rear(self, item):
self.items.append(item)
def remove_front(self):
self.items.pop(0)
def remove_rear(self):
self.items.pop()
def size(self):
return len(self.items)
if __name__ == '__main__':
deque = Deque()
print('双端队列是否为空:', deque.is_empty())
deque.add_front(4)
deque.add_rear(1)
deque.add_front(6)
deque.add_rear(8)
print(deque.size())
deque.remove_rear()
print(deque.size())
网友评论