簡體   English   中英

使用遞歸在Python中反轉堆棧

[英]Reversing a Stack in Python using recursion

我正在做一些練習題。 這個需要在不使用除另一個堆棧之外的任何其他數據結構的情況下反轉堆棧。

我知道我需要一個輔助函數,在原始堆棧為空時附加彈出的數字。

有人能讓我開始嗎? 我被困在這里

def flip_stack(s):
    if not s.is_empty():
        temp = s.pop
        flip_stack(s)

謝謝!

Stack類有poppushis_empty函數。

def reverse(orig, reversel=None):
    if not reversel:
        reversel = []
    reversel.append(orig.pop())
    if orig:
        reverse(orig, reversel)
    return reversel

stack = [1, 2, 3, 4, 5]
stack = reverse(stack)
print stack
[5, 4, 3, 2, 1]
class Stack(object):
    def __init__(self,items=[]):
        self.stack = items

    def is_empty(self):
        return not self.stack

    def pop(self):
        return self.stack.pop()

    def push(self,val):
        self.stack.append(val)

    def __repr__(self):
        return "Stack {0}".format(self.stack)

def flip_stack(stack):
    def flip_stack_recursive(stack,new_stack=Stack()):
        if not stack.is_empty():
            new_stack.push(stack.pop())
            flip_stack_recursive(stack,new_stack)
        return new_stack
    return flip_stack_recursive(stack)


s = Stack(range(5))
print s
print flip_stack(s)

產量

Stack [0, 1, 2, 3, 4]
Stack [4, 3, 2, 1, 0]

你甚至可以使用閉包保持flip_stackstack參數在遞歸函數的范圍內這一事實,因此你不需要它作為內部函數的參數。 例如

def flip_stack(stack):
    def flip_stack_recursive(new_stack):
        if not stack.is_empty():
            new_stack.push(stack.pop())
            flip_stack_recursive(new_stack)
        return new_stack
    return flip_stack_recursive(Stack())

或者,擺脫遞歸函數的所有參數,你的線程堆棧框架將感謝你:

def flip_stack(stack):
    new_stack = Stack()
    def flip_stack_recursive():
        if not stack.is_empty():
            new_stack.push(stack.pop())
            flip_stack_recursive()
    flip_stack_recursive()
    return new_stack

如果stack是本機Python列表,則以下情況有效:

def flip(stack):
    def helper(old_stack, new_stack):
        if old_stack:
            new_stack.append(old_stack.pop())
            return helper(old_stack, new_stack)
        else:
            return new_stack
    return helper(stack[:], [])

stack[:]導致保留原始堆棧。

修改它來處理給定的Stack類應該不難。

這是另一種可能性,使用累加器和輔助函數。 我只使用Stack類中提供的方法,而沒有其他數據結構(例如Python的列表):

def flip_stack(s):
    return flip_stack_helper(s, Stack()) # Stack is your stack class

def flip_stack_helper(s, t):
    if s.is_empty():
        return t
    t.push(s.pop())
    return flip_stack_helper(s, t)

請注意,原始堆棧最后將為空,並返回翻轉的堆棧。

>>> liste = [1, 2, 3, 4, 5]
>>> liste[::-1]
[5, 4, 3, 2, 1]

假設不應該使用數據結構,即使沒有列表來保存最終結果,這是一種可能的解決方案

此處的堆棧將被視為支持以下功能的列表

append(elem)   ---- push(elem) 
pop()          ---- pop() 
if <some stack>---- NotEmpty()

解決方案1:

def flip_stack(s):
    while True:
        if s:
            yield s.pop()
        else:
            return

stack = [1,2,3,4,5]
revStack = [x for x in flip_stack(stack)]

即使您可以在不使用IsEmpty或NotEmpty功能的情況下進行編碼

解決方案2:

def flip_stack(s):
    while True:
        try:
            yield s.pop()
        except IndexError:
            return

注意* *在條件檢查中使用異常是Python中可接受的行為,因為它沒有C ++中的額外開銷

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM