- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStackRecursion.py
67 lines (56 loc) · 1.33 KB
/
StackRecursion.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Python program to reverse a
# stack using recursion
# Recursive funtion that
# inserts an element
# at the bottom of a stack.
definsertAtBottom(stack, item):
ifisEmpty(stack):
push(stack, item)
else:
value=pop(stack)
insertAtBottom(stack, item)
push(stack, value)
# Below is the function that
# reverses the given stack
# using insertAtBottom()
defreverse(stack):
ifnotisEmpty(stack):
value=pop(stack)
reverse(stack)
insertAtBottom(stack, value)
# Function to create a stack.
# It initializes size of a stack as 0
defcreateStack():
stack= []
returnstack
# Function to check if
# the stack is empty
defisEmpty(stack):
returnlen(stack) ==0
# Function to push an
# item to stack
defpush(stack, item):
stack.append(item)
# Function to pop an
# item from stack
defpop(stack):
# if stack is empty
# then error
if(isEmpty(stack)):
print("Stack Underflow!")
exit(1)
returnstack.pop()
# Function to print the stack
defprints(stack):
foriinrange(len(stack) -1, -1, -1):
print(stack[i], end=' ')
stack=createStack()
push( stack, str(4) )
push( stack, str(3) )
push( stack, str(2) )
push( stack, str(1) )
print("Original Stack ")
prints(stack)
reverse(stack)
print("Reversed Stack \n")
prints(stack)