Skip to content

Commit e016a84

Browse files
authored
Create stack.py
1 parent 0e04a63 commit e016a84

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

stack.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Python program to reverse a string using stack
2+
3+
# Function to create an empty stack.
4+
# It initializes size of stack as 0
5+
def createStack():
6+
stack=[]
7+
return stack
8+
9+
# Function to determine the size of the stack
10+
def size(stack):
11+
return len(stack)
12+
13+
# Stack is empty if the size is 0
14+
def isEmpty(stack):
15+
if size(stack) == 0:
16+
return true
17+
18+
# Function to add an item to stack .
19+
# It increases size by 1
20+
def push(stack,item):
21+
stack.append(item)
22+
23+
#Function to remove an item from stack.
24+
# It decreases size by 1
25+
def pop(stack):
26+
if isEmpty(stack): return
27+
return stack.pop()
28+
29+
# A stack based function to reverse a string
30+
def reverse(string):
31+
n = len(string)
32+
33+
# Create a empty stack
34+
stack = createStack()
35+
36+
# Push all characters of string to stack
37+
for i in range(0,n,1):
38+
push(stack,string[i])
39+
40+
# Making the string empty since all
41+
#characters are saved in stack
42+
string=""
43+
44+
# Pop all characters of string and
45+
# put them back to string
46+
for i in range(0,n,1):
47+
string+=pop(stack)
48+
49+
return string
50+
51+
# Driver program to test above functions
52+
string="GeeksQuiz"
53+
string = reverse(string)
54+
print("Reversed string is " + string)
55+
56+
# This code is contributed by Yash

0 commit comments

Comments
 (0)