C++ C+;中有序链表类的插入函数有问题+;

C++ C+;中有序链表类的插入函数有问题+;,c++,pointers,linked-list,C++,Pointers,Linked List,我有一个模板类OList,它是一个有序链表(元素按升序排序)。它有一个名为void insert(const T&val)的函数,用于将元素插入列表中的正确位置。例如,如果我有一个整数列表,其值为{1,3,5},并称为insert(4),则4将插入3和5之间,使OList{1,3,4,5} 现在,当将元素插入空的olist时,我所做的工作很好。但是,当我使用以下代码时: OList<char> list; for (int i = 0; i < 3; i++) { li

我有一个模板类OList,它是一个有序链表(元素按升序排序)。它有一个名为
void insert(const T&val)
的函数,用于将元素插入列表中的正确位置。例如,如果我有一个整数列表,其值为
{1,3,5}
,并称为
insert(4)
,则4将插入3和5之间,使OList
{1,3,4,5}

现在,当将元素插入空的olist时,我所做的工作很好。但是,当我使用以下代码时:

OList<char> list;
for (int i = 0; i < 3; i++) {
    list.insert('C'); 
    list.insert('A');
}
printInfo(list);
相反,它输出:

List = { A,C,C,C, 
然后是运行时错误

我已经花了大约5个小时来处理这个问题,但我似乎没有取得任何进展(除了得到不同的错误输出和错误)


有三段相关的代码:OList的默认构造函数、运算符您正在通过值将指向pre的指针传递到findInsertPoint,因此它被复制,函数更改指针的副本,当函数返回时,它仍然是旧的pre,而不是函数内部的pre


如果要更改指针,必须将指针传递给函数的指针(或对指针的引用)。

Gah,我是个白痴!我将参数类型更改为
Node*&pre
,它工作得非常好。谢谢
List = { A,C,C,C, 
// default constructor
OList() {
    size = 0;
    headNode = new Node<T>;
    lastNode = new Node<T>;
    headNode->next = lastNode;
    lastNode->next = NULL;
}


void insert(const T & val) {
    if ( isEmpty() ) {
        lastNode->data = val;
    }
    else {
        Node<T> * pre = headNode;
        Node<T> * insertPoint = findInsertPoint(pre, val);
        Node<T> * insertNode = new Node<T>;
        insertNode->data = val;
        insertNode->next = insertPoint;
        pre->next = insertNode;

        // why is pre equal to headNode? 
        // I thought I changed that when using it
        // with findInsertPoint()
        cout << (pre == headNode) << endl;
    }

    size++;
}

// returns the node AFTER the insertion point
// pre is the node BEFORE the insertion point
Node<T> * findInsertPoint(Node<T> * pre, const T & val) {
    Node<T> * current = pre->next;

    for (int i = 0; (i < getSize()) && (val > current->data); i++) {
        pre = current;
        current = current->next;
    }

    return current;
}