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

时间:2011-03-01 22:01:54

标签: c++ pointers linked-list

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

现在,在将元素插入EMPTY OLIST时,我的工作正常。但是,当我使用以下代码时:

OList<char> list;
for (int i = 0; i < 3; i++) {
    list.insert('C'); 
    list.insert('A');
}
printInfo(list);

printList(list)应输出:

List = { A,A,A,C,C,C }  Size = 6        Range = A...C

相反,它输出:

List = { A,C,C,C, 

后面是运行时错误。

我现在已经搞乱了大约5个小时,但我似乎没有取得任何进展(除了获得不同的错误输出和错误)。

有三个相关的代码片段:OList的默认构造函数,运算符&lt;&lt;,printInfo(),insert(),以及用于插入的辅助函数,用于查找插入元素的节点。我认为没有理由提供运营商&lt;&lt;也不是printInfo()因为这些似乎在其他地方工作得很好。

// 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;
}

lastNode只是列表中的最后一个节点。 headNode是一个“虚拟节点”,不包含任何数据,仅用作列表的起始位置。

先谢谢了。我真的很尴尬要求在互联网上提供家庭作业帮助,特别是因为我确定主要的问题是我对指针缺乏透彻的理解。

1 个答案:

答案 0 :(得分:1)

您正在将指针传递给findInsertPoint,因此它被复制,并且该函数会更改指针的副本,当函数返回时,它仍然是旧的pre,而不是函数内部的pre。

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