视频里的代码有问题。多出需要更改。以下是根据教学视频更改过的代码。
class Stack():
def __init__(self, size):
self.stack = []
self.size = size
self.top = -1
def push(self, content):
if self.isFull():
print "Stack is full"
else:
self.stack.append(content)
self.top = 1
def pop(self):
if self.isEmpty():
print "Stack is empty"
else:
self.stack.pop()
self.top -= 1
def isFull(self):
if self.top 1 == self.size:
return True
else:
return False
def isEmpty(self):
if self.top == -1:
return True
else:
return False
def printStackInfo(aStack):
print "isEmpty:t{0}".format(aStack.isEmpty())
print "isFull:tt{0}".format(aStack.isFull())
print "top:tt{0}".format(aStack.top)
print "stack:tt{0}".format(aStack.stack)
print "1. Initialise a stack with a size of 2, i.e. store at most 2 elements"
s = Stack(2)
printStackInfo(s)
print "n2. Push 'a'"
s.push('a')
printStackInfo(s)
print "n3. push 'b'"
s.push('b')
printStackInfo(s)
print "n4. push 'c'"
s.push('c')
printStackInfo(s)
print "n5. pop the top element"
s.pop()
printStackInfo(s)
print "n6. pop the top element"
s.pop()
printStackInfo(s)
print "n7. pop the top element"
s.pop()
printStackInfo(s)
视频里的代码没有删除out()中指定的元素,元素依然在stack中。那么out过后再append就会出问题。把stack打印出来就能看到问题在哪儿了。
class Queue():
def __init__(self, size):
self.queue = []
self.size = size
self.head = 0
self.tail = 0
def isEmpty(self):
if self.head == self.tail:
return True
else:
return False
def isFull(self):
if self.tail - self.head == self.size: ####
return True
else:
return False
def inQueue(self, content):
if self.isFull():
print "Queue is full"
else:
self.queue.append(content)
self.tail = 1
def outQueue(self):
if self.isEmpty():
print "Queue is empty"
else:
self.queue.remove(self.queue[0])
self.tail -= 1
def printQueueInfo(aQueue):
print "isEmpty:t{0}".format(aQueue.isEmpty())
print "isFull:tt{0}".format(aQueue.isFull())
print "head:tt{0}".format(aQueue.head)
print "tail:tt{0}".format(aQueue.tail)
print "queue:tt{0}".format(aQueue.queue)
print "1. Initialise a stack with a size of 2, i.e. store at most 2 elements"
q = Queue(2)
printQueueInfo(q)
print "n2. Add 'a'"
q.inQueue('a')
printQueueInfo(q)
print "n3. Add 'b'"
q.inQueue('b')
printQueueInfo(q)
print "n4. Remove 'a'"
q.outQueue()
printQueueInfo(q)
print "n5. Add 'c'"
q.inQueue('c')
printQueueInfo(q)