实现队列 栈 双端队列

以下都是用list来实现的

 

实现Stack

# Implement a Stack in 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):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items) - 1]

    def size(self):
        return len(self.items)


s = Stack()

print(s.is_empty())

s.push(4)
s.push('dog')
print(s.peek())

s.push(True)

print(s.size())
print(s.is_empty())

s.push(8.4)

print(s.pop())
print(s.pop())
print(s.size())
View Code

 

实现Queue

# Implement a Queue in Python
# 工程中一般不用Queue, 用双端队列Deque(Double-end Queue),因为Deque已经有Queue的功能

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):
        return self.items.pop()

    def size(self):
        return len(self.items)


q = Queue()

print(q.is_empty())

q.enqueue(4)
q.enqueue('dog')
q.enqueue(True)
print(q.size())
print(q.is_empty())

print(q.dequeue())

print(q.size())
View Code

 

实现双端对列

# Implement a deque in Python

class Deque(object):
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []

    def add_front(self, item):
        self.items.append(item)

    def add_rear(self, item):
        self.items.insert(0, item)

    def remove_front(self):
        return self.items.pop()

    def remove_rear(self):
        return self.items.pop(0)

    def size(self):
        return len(self.items)


d = Deque()
print(d.is_empty())
d.add_rear(4)
d.add_rear('dog')
d.add_front('cat')
print(d.size())

print(d.is_empty())
d.add_rear(8.4)

print(d.remove_rear())
print(d.remove_front())
View Code

 

posted @ 2024-05-09 19:23  tslam  阅读(3)  评论(0编辑  收藏  举报