开发者

How can a string can be reversed using the stack?

How can a st开发者_JS百科ring or char array be reversed using the stack?


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.


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


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


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()


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".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜