Mahesh
Mahesh

Reputation: 8892

How can a string can be reversed using the stack?

How can a string or char array be reversed using the stack?

Upvotes: 0

Views: 209

Answers (5)

Programmer
Programmer

Reputation: 6753

Push the entire string into a stack. Then pop it out. Remember, a stack is LIFO, so it works

Upvotes: 0

Sadiq
Sadiq

Reputation: 2289

Stacks are LIFO (Last In First Out).

So when you push the characters of the string "Hello!" one by one onto your stack then pop them one by one, you will end up with "!olleH".

Upvotes: 0

user623879
user623879

Reputation: 4142

Just push all the characters onto the stack from char[0] to char[n] and then pop them off the stack back in the opposite order char[0]=pop() to char[n]=pop()

Upvotes: 0

SecretMarmoset
SecretMarmoset

Reputation: 101

Push the whole string onto the stack, one element at a time. Then pop the whole string off of the stack, one element at a time. The string is now reversed.

Upvotes: 6

Steven Feldman
Steven Feldman

Reputation: 841

Since a stack is first in, Last out. You take each character and push it on the stack, then pop of each character.

For Example the Word Testing, would push on g,n,i,t,e,s,t and pop off to form gnitest

Upvotes: 0

Related Questions