C++: Reverse with a stack

Use a stack to reverse a list of words.

What to build

A program that shows why a stack reverses order.

Requirements

  • Read words until the input ends, pushing each onto a stack<string>.
  • Print them in reverse order, one per line.

Input

Words separated by spaces.

Output

One word per line.

Constraints

There are from 1 to 1000 words.

Example

Input:

a b c

Output:

c
b
a

Why it works

The last word pushed is the first to come off, so emptying the stack reverses the list.

Examples

Example 1 · Input
a b c
Expected output
c
b
a
Example 2 · Input
one
Expected output
one

Hints

Hint 1

Push each word.

Hint 2

Read top, then pop, until the stack is empty.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main() {
    stack<string> s;
    string word;
    while (cin >> word) {
        s.push(word);
    }
    while (!s.empty()) {
        cout << s.top() << endl;
        s.pop();
    }
    return 0;
}

Lesson: Stacks, queues and pairs →