'Returning elements to stack in original order without using temporary stack

I have a stack S containing n elements and a queue Q that is initially empty. I have to implement an algorithm that uses Q to scan S to see if it contains a certain element x, with the additional constraint that my algorithm must return the elements back to S in their original order. The compulsion is that I may only use S, Q, and a constant number of other variables.

I have implemented this algorithm having used a temporary stack to hold elements and then return them to the original stack in their original order but how do I accomplish this task without using a temporary stack?

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)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source