【问题标题】:Returning elements to stack in original order without using temporary stack在不使用临时堆栈的情况下按原始顺序将元素返回到堆栈
【发布时间】:2022-01-06 14:30:30
【问题描述】:

我有一个包含 n 个元素的堆栈 S 和一个最初为空的队列 Q。我必须实现一个算法,该算法使用 Q 来扫描 S 以查看它是否包含某个元素 x,还有一个额外的约束是我的算法必须以原始顺序将元素返回给 S。强制是我只能使用 S、Q 和恒定数量的其他变量。

我已经实现了这个算法,它使用一个临时堆栈来保存元素,然后将它们按原始顺序返回到原始堆栈,但是我如何在不使用临时堆栈的情况下完成这项任务?

if __name__ == '__main__':
    
    def scan(S, Q, x):
        
        for i in range(10):
            S.push(i)
        
        S1 = ArrayStack()
        flag = False
        
        for i in range(len(S)):
            Q.enqueue(S.pop())
            if Q.first() == x:
                flag = True
                print("Your desired element has been found:", Q.first())
                S1.push(Q.dequeue())
                break
            else:
                S1.push(Q.dequeue())
                
        if flag == False: 
            print("Sadly, your desired element could not be found.")
                
        
        for i in range(len(S1)):
            S.push(S1.pop())
         
        
    scan(ArrayStack(), LinkedQueue(), 9)

【问题讨论】:

  • 你可以使用递归吗?虽然以某种方式作弊
  • 他们要求固定数量的其他变量,所以如果我们的递归程序的复杂性保持不变,那么也许

标签: python-3.x data-structures queue stack


【解决方案1】:

诀窍是首先将队列中的元素放回堆栈中-这将使它们以相反的顺序放置-然后再次为相同数量的值重复该过程:将它们从堆栈中弹出到队列中然后再次将队列刷新回堆栈。现在它们将恢复原来的顺序。

不确定函数的签名是否已经像那样给你,但我不会将Q 作为参数传递,因为它只服务于函数的算法,而不是调用者。另一方面,我不会在函数内部初始化堆栈,而是让调用者处理填充堆栈。这样调用者就可以控制调用函数的堆栈数据。

所以你可以这样做:

def scan(S, x):
    Q = LinkedQueue()  # Create the queue here
    
    found = False
    for i in range(len(S)):
        Q.enqueue(S.pop())
        found = Q.first() == x
        if found:
            break
    i += 1  # The number of values that are currently in the queue
    # Flush the queue on the stack
    for j in range(i):
        S.push(Q.dequeue())
    # They are reversed on the stack, so remove them again
    for j in range(i):
        Q.enqueue(S.pop())
    # and finally flush the queue again
    for j in range(i):
        S.push(Q.dequeue())
    return found

这样调用:

S = ArrayStack()
# Initialise the stack here
for i in range(10):
    S.push(i)    
# Get the boolean result from the function call
found = scan(S, 12)
# Use it to display a message
if found:
    print("Your desired element has been found")
else:
    print("Sadly, your desired element could not be found.")

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 2021-09-03
    • 2016-08-30
    • 2021-12-25
    • 2016-03-07
    相关资源
    最近更新 更多