Skip to content

Commit 576faf8

Browse files
committed
To reverse a string using stack
1 parent a1433fd commit 576faf8

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#Write a program that take input as string stack and return the reverse of that string in python
2+
3+
class Stack():
4+
def __init__(self):
5+
self.items = []
6+
# this function will take the item and push onto the top of the stack
7+
def push(self, item):
8+
return self.items.append(item)
9+
# this function pop will take out the top element from the stack
10+
def pop(self):
11+
return self.items.pop()
12+
# to check if the stack if empy without this we can't reverse the given string.
13+
def is_empty(self):
14+
return self.items == []
15+
# this function is optional it will just return to top of the stack when called
16+
def peek(self):
17+
if not is_empty():
18+
return self.items[-1]
19+
20+
def _reverse_(Stack, input_str_):
21+
# loop through the string then push it into the stack then
22+
# pop the item fro tne stack append to an empty string variable
23+
24+
for i in range(len(input_str_)):
25+
26+
Stack.push(input_str_[i])
27+
# this empty string is where we are going to store the reversed string
28+
result = ''
29+
while not Stack.is_empty():
30+
result = result + Stack.pop()
31+
return result
32+
33+
34+
stack = Stack()
35+
#input_str_ = ' Abdoulaye'
36+
input_str_= input("Enter the string to reverse: ")
37+
print(_reverse_(stack, input_str_))
38+
# Enter the string to reverse: Hello world
39+
# dlrow olleH

0 commit comments

Comments
 (0)