Walking with Iterators

Lab C++ Intermediate 20 points

Read n integers into a list<int>. Using iterators, remove every element equal to the one before it (keep the first of each run), then print the list.

Input

Line 1: n. Line 2: n integers.

Output

One line.

Example

Input

8
1 1 2 2 2 3 1 1

Output

1 2 3 1
Sample input available Sample output available
Editor
C++

Hints

erase returns an iterator to the next element - use it instead of incrementing.

Solution explanation

Erasing invalidates the erased iterator, so always continue from the returned one.

Show solution
#include <iostream>
#include <list>
using namespace std;

int main() {
    int n;
    cin >> n;
    list<int> l;
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        l.push_back(x);
    }
    auto it = l.begin();
    if (it != l.end()) {
        auto prevIt = it++;
        while (it != l.end()) {
            if (*it == *prevIt) {
                it = l.erase(it);
            } else {
                prevIt = it++;
            }
        }
    }
    bool first = true;
    for (int x : l) {
        cout << (first ? "" : " ") << x;
        first = false;
    }
    cout << "\n";
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD