From d5acc58069e1c2d65255032fe1542a2f0dbad40b Mon Sep 17 00:00:00 2001 From: Sheetal Neeraj <42382485+sheetalneeraj@users.noreply.github.com> Date: Mon, 2 Oct 2023 21:48:56 +0530 Subject: [PATCH] Create reverse_stack.py --- data_structures/stacks/reverse_stack.py | 52 +++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 data_structures/stacks/reverse_stack.py diff --git a/data_structures/stacks/reverse_stack.py b/data_structures/stacks/reverse_stack.py new file mode 100644 index 000000000..233735fb6 --- /dev/null +++ b/data_structures/stacks/reverse_stack.py @@ -0,0 +1,52 @@ +from stack import Stack # Assuming you have a Stack class defined in 'stack.py' + +def reverse_stack(stack): + """ + Reverse the elements of a stack using another stack. + + Args: + stack (Stack): The input stack to be reversed. + + Example: + + >>> s = Stack() + >>> s.push(1) + >>> s.push(2) + >>> s.push(3) + >>> reverse_stack(s) + >>> reversed_stack = [] + >>> while not s.is_empty(): + ... reversed_stack.append(s.pop()) + >>> reversed_stack + [3, 2, 1] + """ + if stack.is_empty(): + return + + reversed_stack = Stack() + + while not stack.is_empty(): + item = stack.pop() + reversed_stack.push(item) + + while not reversed_stack.is_empty(): + item = reversed_stack.pop() + stack.push(item) + +if __name__ == "__main__": + from doctest import testmod + + testmod() + + s = Stack() + s.push(1) + s.push(2) + s.push(3) + + reverse_stack(s) + + reversed_stack = [] + while not s.is_empty(): + reversed_stack.append(s.pop()) + + print("Reversed Stack:", reversed_stack)