Using Stack to reverse a word

Using a Stack structure (LIFO) can be handy for reversing a word. I'll show you how you can do that with python:

class Stack:
stackArray = []
def push(self, j):
self.stackArray.append(j)
def pop(self):
return self.stackArray.pop()
def peek(self):
return self.stackArray[-1]
class Reverser:
def __init__(self, input):
self.inputStr = input
self.outputStr = ''
def doRev(self):
inputSize = len(self.inputStr)
stack = Stack()
#get chars and push them to stack
for x in range(0, inputSize):
char = self.inputStr[x]
stack.push(char)
#reverse
while stack.stackArray:
char = stack.pop()
self.outputStr = self.outputStr + char
return self.outputStr




Comments

Popular posts from this blog

Spring JPA : Using Specification with Projection

Chip input using Reactive Form