Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Use a stack to write a function reverse_words(sentence) that reverses the order of the words of a sentence, so that "one two three" becomes "three two one".
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Push every word on a stack, and pop them all. The last word comes off first.
Check. one two three gives three two one. An empty sentence has no words, so the result is the empty text. One word gives itself.
Answer: three two one, '' and single.
Log in to join the discussion.
Loading…