Group_Coder

Write a function that takes a string as input and returns the reversed string using a stack.

Jul 24th, 2023
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.47 KB | None | 0 0
  1. def reverse_string(input_string):
  2. stack = []
  3. reversed_string = ""
  4.  
  5. # Push each character of the input string onto the stack
  6. for char in input_string:
  7. stack.append(char)
  8.  
  9. # Pop characters from the stack to construct the reversed string
  10. while stack:
  11. reversed_string += stack.pop()
  12.  
  13. return reversed_string
  14.  
  15. # Example usage:
  16. input_str = "python"
  17. reversed_str = reverse_string(input_str)
  18. print(reversed_str) # Output: "nohtyp"
Advertisement
Add Comment
Please, Sign In to add comment