用栈功能实现队列功能
- 问题描述> 利用栈去实现队列的基本功能
- 问题解析> - 准备两个栈
- Stack_Date用于平常数据的压入和弹出数据
- Stack_Help用于使用栈的功能实现队列功能
- 将Stack_Date倒置得到Stack_Help
- 得到Stack_Help的栈顶元素为队列功能的首项元素信息: Stack_help_top
- 删除Stack_Help的栈顶元素为队列功能的首项元素信息: Stack_help_pop
- 代码实现
- 封装错误
python class None_Stack_Error(Exception): def __str__(self): return "There are no elements available in the stack"
当范围栈顶元素时/删除栈顶元素时栈不能为空栈
- 封装错误
list实现栈功能```python class Stack(object):
def init(self): self.__list = []
@property def Append_Stack_Number(self): return self.__list
@Append_Stack_Number.setter def Append_Stack_Number(self, Append_Stack_Number): self.__list.append(Append_Stack_Number)
@property def is_empty(self): return self.__list == []
def push(self, item): self.__list.append(item)
@property def pop(self): if self.is_empty:
raise None_Stack_Error
else:
return self.__list.pop()
@property def top(self): if self.is_empty:
raise None_Stack_Error
else:
return self.__list[-1]
def str(self): return self.Append_Stack_Number
> **测试代码** > ```python if __name__ == '__main__': new_Stack = Stack() new_Stack.Append_Stack_Number = 2 new_Stack.Append_Stack_Number = 12 print(new_Stack.top) print(new_Stack.is_empty) # 12 # False
队列功能实现```python class StackQueue: def init(self): self._Stack_Date = Stack() self.Stack_Help = Stack() self.len = 0 self.Stack_Append_Number = None
@property def StackAppend_Number(self): if self._Stack_Append_Number is not None:
self._Stack_Append_Number_ = None
return
@property def StackDate(self): return self._Stack_Date.str()
@StackAppend_Number.setter def Stack_Append_Number(self, Stack_Append_Number): self._Stack_Append_Number = StackAppend_Number self._Append_Stack(self.Stack_Append_Number) self.Stack_Clear()
@property def StackHelp(self): return self._Stack_Help.str()
@property def Stackhelp_top(self): return self._Stack_Help.top
@property def Stackhelp_pop(self): self._len = list(self.Stack_Help.str()) try:
return self._Stack_Help_.pop
except None_Stack_Error:
return None
@property def isempty(self): return self._Stack_Help.is_empty
def Append_Stack(self, Stack_Append_Number): self.Stack_Date.AppendStack_Number = _Stack_Append_Number
def Stack_Clear(self): self.Stack_Help = Stack() for i in list(self.Stack_Date.str())[::-1]:
self._Stack_Help_.Append_Stack_Number = i
> **测试代码** > ```python if __name__ == '__main__': New_Stack_Queue = Stack_Queue() New_Stack_Queue.Stack_Append_Number = 12 New_Stack_Queue.Stack_Append_Number = 13 New_Stack_Queue.Stack_Append_Number = 134 print(New_Stack_Queue.Stack_Help) print(New_Stack_Queue.Stack_help_pop) print(New_Stack_Queue.Stack_help_pop) print(New_Stack_Queue.Stack_help_pop) print(New_Stack_Queue.Stack_help_pop) """ [134, 13, 12] 12 13 134 None """