📜  反转堆栈的Python程序

📅  最后修改于: 2021-09-07 03:00:11             🧑  作者: Mango

堆栈是一种线性数据结构,适用于 LIFO 概念。 LIFO 代表后进先出。在栈中,插入和删除都是可能的,一端称为栈顶。

在本文中,我们将看到如何使用Python反转堆栈。

算法:

  • 定义一些堆栈的基本函数,如 push()、pop()、show()、empty(),基本操作如分别在堆栈中添加一个项目、删除堆栈中的一个项目、显示堆栈、检查给定的堆栈是空与否。
  • 定义两个递归函数BottomInsertion() 和Reverse()。

BottomInsertion() :此方法在堆栈底部追加元素,BottomInsertion 接受两个值作为参数,第一个是堆栈,第二个是元素,这是一个递归方法。

# insert element at the bottom of the stack
def BottomInsert(s, value):
    # if stack is empty then call push() method.
    if s.empty():  
        s.push(value)
        
    # if stack is not empty then execute else
    # block
    else:
    
        # remove the element and store it to
        # popped  
        popped = s.pop()
        
        # invoke it self and pass stack and value 
        # as an argument.
        BottomInsert(s, value)
        
        # append popped item in the bottom of the stack 
        s.push(popped)

Reverse() :该方法是堆栈的反向元素,该方法接受堆栈作为参数 Reverse() 也是一个 Recursive()函数。 Reverse() 调用BottomInsertion() 方法完成对堆栈的反向操作。

# Reverse()
def Reverse(s): 

    # check the stack is empty of not  
    if s.empty():
    
        # if empty then do nothing
        pass
        
    # if stack is not empty then 
    else:
    
        # pop element and stare it to popped
        popped = s.pop()
        
        # call it self ans pass stack as an argument
        Reverse(s)
        
        # call BottomInsert() method and pass stack
        # and popped element as an argument
        BottomInsert(s, popped)

下面是实现。

Python3
# create class for stack
class Stack:
  
    # create empty list
    def __init__(self):
        self.Elements = []
          
    # push() for insert an element
    def push(self, value):
        self.Elements.append(value)
        
    # pop() for remove an element
    def pop(self):
        return self.Elements.pop()
      
    # empty() check the stack is empty of not
    def empty(self):
        return self.Elements == []
      
    # show() display stack
    def show(self):
        for value in reversed(self.Elements):
            print(value)
  
# Insert_Bottom() insert value at bottom
def BottomInsert(s, value):
    
    # check the stack is empty or not
    if s.empty(): 
          
        # if stack is empty then call
        # push() method.
        s.push(value)
          
    # if stack is not empty then execute
    # else block
    else:
        popped = s.pop()
        BottomInsert(s, value)
        s.push(popped)
  
# Reverse() reverse the stack
def Reverse(s):
    if s.empty():
        pass
    else:
        popped = s.pop()
        Reverse(s)
        BottomInsert(s, popped)
  
  
# create object of stack class
stk = Stack()
  
stk.push(1)
stk.push(2)
stk.push(3)
stk.push(4)
stk.push(5)
  
print("Orginal Stack")
stk.show()
  
print("\nStack after Reversing")
Reverse(stk)
stk.show()


输出:

Orginal Stack
5
4
3
2
1

Stack after Reversing
1
2
3
4
5