0% found this document useful (0 votes)
101 views3 pages

Practical - 14 - Reverse A String Using Stack

Practical_14_reverse a string using stack

Uploaded by

vishwajeet.myjob
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views3 pages

Practical - 14 - Reverse A String Using Stack

Practical_14_reverse a string using stack

Uploaded by

vishwajeet.myjob
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

# Python program to to reverse a string using stack

# Class representing a node in the class

class Node:

def __init__(self,data):

self.data = data

self.next = None

# Class to implement stack using a singly linked list

class Stack:

def __init__(self):

self.top = None

# Function to check if the stack is empty

def is_empty(self):

# If head is None, the stack is empty

return self.top is None

# Function to push an element onto the stack

def push(self,data):

# Create a new node with given data

new_node = Node(data)

if self.top is None:

self.top = new_node

else:

new_node.next = self.top

self.top=new_node

# Function to remove the top element from the stack


def pop(self):

if not self.is_empty():

temp = self.top.data

self.top = self.top.next

return temp

# Creating a stack

st = Stack()

str=input("\nEnter the string to be reversed: ")

#String reversal

#Pushing individual characters from string into the stack

for ch in str:

st.push(ch)

rlist=[]

while (not st.is_empty()):

rlist.append(st.pop())

rstr=''.join(rlist)

print("\nReversed String is: ",rstr)

You might also like