Python 栈、队列、双端列表、链表实现
# 栈
class Stack():
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return len(self.items) - 1
def isEmpty(self):
return self.items == []
def size(self):
return len(self.items)
# 队列
class Queuee(object):
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def isEmpty(self):
return self.items == []
def size(self):
return len(self.items)
# 双端队列
class Deque():
"""
双端队列
队尾-------队头
"""
def __init__(self):
self.items = []
def addFront(self, item):
# 从哪进从哪出,想从队头取123,就得冲队尾插入123才行
self.items.insert(0, item)
def addRear(self, item):
self.items.append(item)
def removeFront(self):
# 出来了,
return self.items.pop()
def removeRear(self):
return self.items.pop(0)
def isEmpty(self):
return self.items == []
def size(self):
return len(self.items)
# 链表
class Node():
def __init__(self, item):
self.items = item
self.next = None
class Link():
def __init__(self):
self._head = None
def add(self, item): # 新创建节点指向head指向,head断开指向新建node
node = Node(item)
node.next = self._head
self._head = node
def travel(self):
link = ''
cur = self._head
while cur:
link += (str(cur.items) + ' ')
cur = cur.next
print(link)
def isEmpty(self):
return self._head == None
def size(self):
cur = self._head
count = 0
while cur:
count += 1
cur = cur.next
return count
def append(self, item):
node = Node(item)
cur = self._head
p = Node
while cur:
p = cur
cur = cur.next
p.next = node
# 定向删除,定向插入,不再提
link = Link()
link.add(2)
link.add(3)
link.add(4)
link.append(10)
link.travel()
print(link.isEmpty(), link.size())