Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added code in Stack folder Reverse Stack Program #94

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions stack/ReverseaStackUsingRecusion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
def insertAtBottom(stack, item):
if isEmpty(stack):
push(stack, item)
else:
temp = pop(stack)
insertAtBottom(stack, item)
push(stack, temp)

# Below is the function that
# reverses the given stack
# using insertAtBottom()


def reverse(stack):
if not isEmpty(stack):
temp = pop(stack)
reverse(stack)
insertAtBottom(stack, temp)

# Below is a complete running
# program for testing above
# functions.

# Function to create a stack.
# It initializes size of stack
# as 0


def createStack():
stack = []
return stack

# Function to check if
# the stack is empty


def isEmpty(stack):
return len(stack) == 0

# Function to push an
# item to stack


def push(stack, item):
stack.append(item)

# Function to pop an
# item from stack


def pop(stack):

# If stack is empty
# then error
if(isEmpty(stack)):
print("Stack Underflow ")
exit(1)

return stack.pop()

# Function to print the stack


def prints(stack):
for i in range(len(stack)-1, -1, -1):
print(stack[i], end=' ')
print()

# Driver Code


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 ")
prints(stack)