[ create a new paste ] login | about

Link: http://codepad.org/xYcvnaSV    [ raw code | output | fork ]

anmartex - C++, pasted on Sep 22:
#include <iostream>

struct ilist {
    int data;
    ilist* next;
};

//-----------------------------------------------------------------------------
std::ostream& operator << (std::ostream& os, const ilist* list) {
    for (; list; list = list->next) {
        os << list->data << ' ';
    }
    return os;
}
//-----------------------------------------------------------------------------
bool func(int i) {
    return (i % 2) == 0;
}
//-----------------------------------------------------------------------------
ilist* push_front(ilist*& list, int data) {
    ilist* node = new ilist;
    node->data = data;
    node->next = list;
    list = node;
    return list;
}
//-----------------------------------------------------------------------------
ilist* list_move(const ilist* head, bool (*com)(int)) {
    ilist* a = NULL, * tail_a, * b = NULL, * tail_b;
    for (; head; head = head->next) {
        // Копируем верхний узел
        ilist* node = new ilist;
        node->data = head->data;
        node->next = NULL;

        // Определяем к какому списку будем добавлять узел
        bool is_com = com(node->data);
        ilist*& c = is_com ? a : b;
        ilist*& tail_c = is_com ? tail_a : tail_b;

        // Если в списке нет ни одного элемент то делаем
        // его первым и хвостовым
        if (c == NULL) {
            c = tail_c = node;
        }
        // Добавляем в хвост отделённый узел. Хвостом соответственно
        // становится добавленный узел
        else {
            tail_c->next = node;
            tail_c = node;
        }
    }
    if (a == NULL) {
        a = b;
    }
    else {
        tail_a->next = b;
    }

    return a;
}
//-----------------------------------------------------------------------------

int main() {
    ilist* source = NULL;
    for (int i = 10; i; --i) {
        push_front(source, i);
    }
    ilist* result = list_move(source, func);

    std::cout << "source: " << source << std::endl
              << "result: " << result << std::endl;

    return 0;
}


Output:
1
2
source: 1 2 3 4 5 6 7 8 9 10 
result: 2 4 6 8 10 1 3 5 7 9 


Create a new paste based on this one


Comments: