summaryrefslogtreecommitdiff
path: root/structures/task8.cpp
blob: 099795d8d15605f5079174beaac68ec1ac32753e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include "stack.h"

using namespace std;

stack *result(stack *&h)
{
    stack *res = NULL;

    while (h)
    {
        stack *tmp = NULL;

        // Будем убирать из стека все повторения его верхнего элемента.
        int el = pop(h);
        // Так как все повторения будут убраны, можно положить 
        // значение в стек с результатом.
        push(res, el);
        while (h)
        {
            int cur = pop(h);
            if (cur != el)
                push(tmp, cur);
        }
        // После выполнения предыдущего цикла, в стеке не осталось
        // значений, равных el. Обновим h и запустим на нём этот же
        // самый алгоритм.
        while (tmp)
            push(h, pop(tmp));
    }

    reverse(res);
    return res;
}

int main()
{
    int n;
    cout << "n = ";
    cin >> n;
    stack *head = NULL;
    char x;
    for (int i = 0; i < n; i++)
    {
        cin >> x;
        push(head, int(x));
    }
    reverse(head);
    stack *res = result(head);
    while (res)
        cout << char(pop(res)) << " ";
    cout << endl;

    return 0;

}