目录
栈的操作及其实现
栈的相关操作 | 栈的内容 | 执行操作后返回值 |
---|---|---|
is_empty() | [] | True |
push(1) push(3) push(5) | [1] [1,3] [1,3,5] | 无返回值 |
pop() | [1,3,5] | 5(从栈顶删除元素) |
peek() | [1,3,5] | 5(返回栈顶元素) |
size() | [1,3] | 2 |
顺序栈
(1)初始化一个空栈
def __init__(self):
self.stack = []
(2)判断是否为空
def is_empty(self):
return not self.stack
(3)向栈中添加元素
def push(self, value):
self.stack.append(value)
(4)输出栈中元素
def pop():
return self.stack.pop()
(5)输出栈顶的元素
def peek(self):
if self.is_empty():
return None
return self.stack[-1]
(6)输出栈中元素的个数
def size(self):
return len(self.stack)
总的代码:
class SeqStack(object):
def __init__(self):
self.stack = []
def is_empty(self):
return not self.stack
def push(self, value):
self.stack.append(value)
def pop(self):
return self.stack.pop()
def peek(self):
if s.is_empty():
return None
return self.stack[-1]
def size(self):
return len(self.stack)
if __name__ == '__main__':
s = SeqStack()
print("The SeqStack if empty: ",s.is_empty())
s.push(1)
s.push(3)
s.push(5)
print("The size of Seqstack is: ", s.size())
print(s.pop())
print(s.pop())
print("The peek of the Seqstack is: ",s.peek())
out:
链式栈
(1)定义
class ChainStack(object):
def __init__(self,value):
self.value = value
self.next = None
(2)初始化
def __init__(self):
self.stack = None # self.stack指向栈顶
(3)判断是否为空
def is_empty(self):
return not self.stack
(4)添加元素
def push(self, value):
s = ChainStack(value)
if self.is_empty():
self.stack = s
else:
s.next = self.stack
self.stack = s
(5)输出栈中的元素
def pop(self):
s = self.stack
self.stack = s.next
return s.value
(6)输出栈顶元素
def peek(self):
return self.stack.value
(7)输出链式栈中节点的个数
def size(self):
s = self.stack
index = 0
while s:
index = index +1
s = s.next
return index
总的代码
#2.链式栈
class ChainStack(object):#定义链式栈
def __init__(self,value):
self.value = value
self.next = None
class CStack(object):
def __init__(self):#初始化一个空栈,self.stack指的是栈顶元素
self.stack = None
def push(self, value):#向栈中添加元素
s = ChainStack(value)
if self.is_empty():
self.stack = s
else:
s.next = self.stack
self.stack = s
def pop(self):#栈中pop最后进入的一个元素
s = self.stack
self.stack = s.next
return s.value
def peek(self):#输出栈中最上面(最后入栈)的元素
return self.stack.value
def is_empty(self):#判断是否为空
return not self.stack
def size(self):
s = self.stack
index = 0
while s:
index =index + 1
s = s.next
return index
if __name__ == '__main__':
stack = CStack()
print(stack.is_empty())
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.peek())
print(stack.pop())
print(stack.pop())
print(stack.peek())
print(stack.size())