class SqStack: def __init__(self): #构造函数 self.data=[] #存放栈中元素,初始为空 def empty(self): #判断栈是否为空 if len(self.data)==0: return True return False def push(self,e): #元素e进栈 def pop(self): #元素出栈 def gettop(self): #取栈顶元素 if __name__ == '__main__': print() print(" 创建空顺序栈st") st=SqStack() print(" st:","空" if st.empty() else "不空") print(" 进栈1-4") st.push(1) st.push(2) st.push(3) st.push(4) print(" st:","空" if st.empty() else "不空") print(" 出栈顺序:",end=' ') while not st.empty(): print(st.pop(),end=' ') print() print(" st:","空" if st.empty() else "不空") print()
时间: 2024-01-14 17:02:38 浏览: 9
这是一个顺序栈的类定义,但是其中的 push、pop、gettop 方法没有实现具体的功能。以下是完整代码,其中加入了这些方法的实现:
```
class SqStack:
def __init__(self):
self.data=[]
def empty(self):
return len(self.data) == 0
def push(self,e):
self.data.append(e)
def pop(self):
if not self.empty():
return self.data.pop()
else:
print('栈已空,无法出栈!')
def gettop(self):
if not self.empty():
return self.data[-1]
else:
print('栈已空,无法取栈顶元素!')
if __name__ == '__main__':
print("创建空顺序栈st")
st=SqStack()
print("st:","空" if st.empty() else "不空")
print("进栈1-4")
st.push(1)
st.push(2)
st.push(3)
st.push(4)
print("st:","空" if st.empty() else "不空")
print("出栈顺序:",end=' ')
while not st.empty():
print(st.pop(),end=' ')
print()
print("st:","空" if st.empty() else "不空")
```
这个代码实现了顺序栈的基本操作:入栈、出栈和取栈顶元素。您可以将其保存到 .py 文件中运行,看看输出结果。