doublyLinkedList编译但执行时崩溃

时间:2016-03-22 16:13:14

标签: c++ linked-list nodes doubly-linked-list

我的doublyLinkedList有效,直到我调用removeAt(int i)函数,但我不知道它有什么问题。

这是我的doublyLinkedList:

class node
{
public:
    node * prev;
    node * next;
    double data;
};

class doublyLinkedList
{
private:
    node * head;
    node * tail;

    node * findAt(int i)
    {
        node * current = head;
        for (int j = 1; j <= i; j++)
        {
            current = current->next;
        }
        return current;
    }

    void removeNode(node * doomedNode)
    {
        if (head == tail && doomedNode == head)
        {
            head = NULL;
            tail = NULL;
            delete doomedNode;
        }
        else if (doomedNode == tail && tail != head)
        {
            tail = tail->prev;
            tail->next = NULL;
            delete doomedNode;
        }
        else if (doomedNode == head && head != tail)
        {
            head = head->next;
            head->prev = NULL;
            delete doomedNode;
        }
        else
        {
            node * ahead = doomedNode->prev;
            node * behind = doomedNode->next;
            ahead->prev = behind;
            behind->next = ahead;
            delete doomedNode;
        }
    }

public:
    doublyLinkedList()
    {
        head = NULL;
        tail = NULL;
    }

    ~doublyLinkedList()
    {
        node * temp;
        while (head != NULL)
        {
            temp = head->next;
            delete head;
            head = temp;
        }
    }

    void addBack(double x)
    {
        node * newItem = new node;
        newItem->data = x;
        if (head == NULL && tail == NULL)
        {
            newItem->prev = NULL;
            newItem->next = NULL;
            head = newItem;
            tail = newItem;
        }
        else
        {
            newItem->prev = tail;
            newItem->next = NULL;
            tail->next = newItem;
            tail = newItem;
        }
    }

    void removeAt(int i)
    {
        node * current = head; node * foundNode; node * deletedNode;
        int j = 1;
        while (current != NULL)
        {
            current = current->next;
            j++;
        }

        if (i >= j && i > 0)
        {
            foundNode = findAt(i);
            removeNode(foundNode);
        }
    }
};

有人可以告诉我有什么问题吗?

0 个答案:

没有答案