如何使我的复制构造函数为双向链接堆栈工作

时间:2016-10-24 05:07:32

标签: c++ stack copy-constructor

您好我有这个复制构造函数,看起来它没有制作正确的副本并抛出错误。错误是:“从gtest_main.cc运行main()  进程以退出代码139结束(由信号11中断:SIGSEGV) “。我正在用google gtest测试这个构造函数.headPtr //指向链中第一个节点的指针; topPtr //指向链中最后一个节点的指针;

模板 DLinkedStack :: DLinkedStack(const DLinkedStack& aStack){

//Points to nodes in orignal chain
    Node<T> *origChainPtr = aStack.headPtr;
    if (origChainPtr == nullptr)
        headPtr = topPtr = nullptr;    // Original bag is empty
    else {

        // Copy first Node
        headPtr = new Node<T>();
        headPtr->setItem(origChainPtr->getItem());

        //Point to first node in new chain
        Node<T> *newChainPtr = headPtr;
        //Point to last node in new chain
        Node<T> *otherChainPtr = topPtr;

        //copy remaining nodes
        while (origChainPtr != nullptr) {
            // Advance original chain pointer
            origChainPtr = origChainPtr->getNext();

            // get next item from original chain
            T nextItem = origChainPtr->getItem();

             //get previous item from original chain
            T prevItem = origChainPtr->getItem();

            // create a new node contaning the next item
            Node<T> *newNodePtr = new Node<T>(nextItem);

            // create a new node contaning the prev item
            Node<T> *newNodePtr1 = new Node<T>(prevItem);

            //Link new node to the end of new chain
            newChainPtr->setNext((newNodePtr));

            //Link new node1 to the begining of new chain
            newChainPtr->setPrev(newNodePtr1);


            // advance pointer to new last node
            newChainPtr = newChainPtr->getNext();

            // advance one forward
            otherChainPtr = otherChainPtr->getNext();

        }
        newChainPtr->setNext(nullptr);    // Flag end of chain
    }
}

0 个答案:

没有答案