Skip to content

Commit b8cfe55

Browse files
committed
Stack Implementation added.
1 parent bd2677d commit b8cfe55

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Stack/StackRecursion.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Python program to reverse a
2+
# stack using recursion
3+
4+
# Recursive funtion that
5+
# inserts an element
6+
# at the bottom of a stack.
7+
def insertAtBottom(stack, item):
8+
if isEmpty(stack):
9+
push(stack, item)
10+
else:
11+
value = pop(stack)
12+
insertAtBottom(stack, item)
13+
push(stack, value)
14+
15+
# Below is the function that
16+
# reverses the given stack
17+
# using insertAtBottom()
18+
def reverse(stack):
19+
if not isEmpty(stack):
20+
value = pop(stack)
21+
reverse(stack)
22+
insertAtBottom(stack, value)
23+
24+
# Function to create a stack.
25+
# It initializes size of a stack as 0
26+
def createStack():
27+
stack = []
28+
return stack
29+
30+
# Function to check if
31+
# the stack is empty
32+
def isEmpty(stack):
33+
return len(stack) == 0
34+
35+
# Function to push an
36+
# item to stack
37+
def push(stack, item):
38+
stack.append(item)
39+
40+
# Function to pop an
41+
# item from stack
42+
def pop(stack):
43+
# if stack is empty
44+
# then error
45+
if(isEmpty(stack)):
46+
print("Stack Underflow!")
47+
exit(1)
48+
49+
return stack.pop()
50+
51+
# Function to print the stack
52+
def prints(stack):
53+
for i in range(len(stack) - 1, -1, -1):
54+
print(stack[i], end = ' ')
55+
56+
stack = createStack()
57+
push( stack, str(4) )
58+
push( stack, str(3) )
59+
push( stack, str(2) )
60+
push( stack, str(1) )
61+
print("Original Stack ")
62+
prints(stack)
63+
64+
reverse(stack)
65+
66+
print("Reversed Stack \n")
67+
prints(stack)

0 commit comments

Comments
 (0)