从链接列表中删除第一个元素

时间:2013-11-28 14:32:21

标签: c++ pointers linked-list

我正在开发自己的链表类。一切正常。 删除功能也有效,但如果我尝试删除第一个元素,则应用程序停止响应。

我不知道,我错了什么。

源代码:

#include <iostream>

using namespace std;

template<class T>
class linkedList {

private:
    struct elem {
        elem* p;  // pointer
        T v;      // value

        elem* next() {
            return p;
        }
    };

    int elems = 0;
    elem* first;

    elem* last() {
        if(first == 0) return 0;

        elem* e = first;
        while(e->p != 0) {
            e = e->p;
        }

        return e;
    }

    elem* getP(int index) {
        int i=0;
        elem* e;

        e->p = first;
        while(i!=index) {
            e = e->p;
            i++;
        }

        return e->p;
    }

public:

    T& get(int index) {
        int i=0;
        elem* e;

        if(elems<index) throw 0x77;

        e->p = first;

        while(i!=index) {
            e = e->p;
            i++;
        }

        return (e->p)->v;
    }

    void add(T el) {
        elem* u = last();
        elem* e = new elem;

        e->p = 0;
        e->v = el;

        if(u == 0) {
            first = e;
        } else {
            u->p = e;
        }

        elems++;
    }

    int size() {
        return elems;
    }

    void remove(int index) {
        if(elems<index) throw 0x77;

        if(index == 0) {
            elem* e = first->p;
            first->p = e->p;
            delete e;
            elems--;
        } else {
            elem* p = getP(index-1);
            elem* e = p->p;
            elem* n = e->p;

            delete e;
            p->p = n;

            elems--;
        }
    }

};

int main()
{
    linkedList<int> myList;

    myList.add(10);
    myList.add(12);
    myList.add(4);
    myList.add(7);

    myList.remove(0);

    cout << myList.get(0) << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:0)

remove(int)方法中,当index为0时,您设置第一个元素的指针,而不是将指针设置为第一个元素:

void remove(int index) {
    if(elems<index) throw 0x77;

    if(index == 0) {
        elem* e = first;
        first = first->p; // Set first instead of first->p
        delete e;
        elems--;
    } else {
        elem* p = getP(index-1);
        elem* e = p->p;
        elem* n = e->p;

        delete e;
        p->p = n;

        elems--;
    }
}

顺便说一句:可能是,你的代码中有更多与此相关的错误,不会导致错误。