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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Post a Comment