一、思维梳理:
二、双向循环链表:
class Node:
def __init__(self,data):
self.data = data
self.next = None
self.prev = None
class DoubleLink:
def __init__(self):
self.size = 0
self.head = None
def is_empty(self):
return self.size == 0
def add_end(self,data):
node = Node(data)
if self.is_empty():
self.head = node
node.next = node
node.prev = node
else:
q = self.head.prev
node.prev = q
node.next = self.head
q.next = node
self.head.prev = node
self.size += 1
def del_end(self):
if self.is_empty():
return
else:
if self.size == 1:
self.head = None
else:
q = self.head.prev
self.head.prev = q.prev
q.prev.next = self.head
self.size -= 1
def show(self):
if self.is_empty():
return
else:
q = self.head
while q.next != self.head:
print(q.data,end=" ")
q = q.next
print(q.data,end=" ")
print()
if __name__ == '__main__':
doubleLink = DoubleLink()
doubleLink.add_end(10)
doubleLink.add_end(20)
doubleLink.add_end(30)
doubleLink.add_end(40)
doubleLink.add_end(50)
doubleLink.show()
doubleLink.del_end()
doubleLink.show()
结果展示:
10 20 30 40 50
10 20 30 40
三、顺序栈:
class Stack:
def __init__(self,capacity):
self.capacity = capacity
self.size = 0
self.data = [None]*capacity
def is_empty(self):
return self.size == 0
def is_full(self):
return self.size == self.capacity
def push(self,data):
if self.is_full():
return
self.data[self.size] = data
self.size += 1
def pop(self):
if self.is_empty():
return
self.size -= 1
def top(self):
if self.is_empty():
return
return self.data[self.size-1]
def get_size(self):
return self.size
def show(self):
for i in range(self.size-1,-1,-1):
print(self.data[i],end=" ")
print()
if __name__ == '__main__':
stack = Stack(100)
stack.push(10)
stack.push(20)
stack.push(30)
stack.push(40)
stack.show()
stack.pop()
stack.show()
结果展示:
40 30 20 10
30 20 10
四、链式栈:
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.size = 0
self.top = None
def is_empty(self):
return self.size == 0
def push(self,data):
node = Node(data)
node.next = self.top
self.top = node
self.size += 1
def pop(self):
if self.is_empty():
return
else:
self.top = self.top.next
self.size -= 1
def get_top(self):
if self.is_empty():
return
return self.top.data
def get_size(self):
return self.size
def show(self):
if self.is_empty():
return
q = self.top
while q:
print(q.data,end=" ")
q = q.next
print()
if __name__ == '__main__':
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
stack.push(40)
stack.push(50)
stack.push(60)
stack.show()
stack.pop()
stack.show()
print(stack.get_top())
print(stack.get_size())
结果展示:
60 50 40 30 20 10
50 40 30 20 10
50
5