C++中掌握线性链表的基本操作:插入、删除、查找等运算

1个回答

  • #include

    #include

    struct CListNode {

    int value;

    CListNode* next;

    };

    struct CList {

    CList() {

    head.next = NULL;

    }

    void build(int n, void (*input_func)(int&)) {

    CListNode* p = head;

    for (int i = 0; i < n; i++) {

    CListNode* node = new CListNode();

    input_func(node->value);

    node->next = NULL;

    p->next = node;

    p = node;

    }

    }

    void visit(void (*output_func)(int&)) {

    CListNode* p = head.next;

    while (p != NULL) {

    output_func(p->value);

    p = p->next;

    }

    }

    struct Iterator {

    Iterator(CListNode* pv, CListNode* p) : prev(pv), node(p) {}

    bool hasNext() const { return node != NULL; }

    intgetValue() { return node->value; }

    void operator++(int) { prev = node; node = node->next; }

    CListNode* prev;

    CListNode* node;

    };

    Iterator begin()

    { return Iterator(&head, head.next); }

    void insertBefore(Iteratoriter, int value) {

    CListNode* p = new CListNode();

    p->value = value;

    p->next = iter.node;

    iter.prev->next = p;

    iter.prev = p;

    }

    void erase(Iteratoriter) {

    CListNode* p = iter.node;

    iter.node = p->next;

    iter.prev->next = iter.node;

    delete p;

    }

    CListNode head;

    };

    void IterOutput(intvalue) {

    printf("%d ", value);

    }

    void IterInput(intvalue) {

    scanf("%d", value);

    }

    int main(int argc, char* args[])

    {

    const int count = 10;

    CList l;

    l.build(count, IterInput);

    l.visit(IterOutput);

    CList::Iterator iter = l.begin();

    while (iter.hasNext()) {

    if ((iter.getValue()%2) == 0) {

    l.insertBefore(iter, -1);

    iter++;

    } else {

    l.erase(iter);

    }

    }

    l.visit(IterOutput);

    ::system("pause");

    return 0;

    }混蛋啊,这个需求太蛋疼了。。写死我了。。。