0

The problem I am running into is trying to properly use pointers to reduce the amount of items in a linked list to a frequency of 1.

The code I am getting is below:

template<class ItemType>
bool LinkedBag<ItemType>::flatten()
{
    bool changeFlag = false;
    int counter = 0;
    int size = getCurrentSize();
    ItemType store;
    Node<ItemType>* curPtr = headPtr;
    Node<ItemType>* tempPtr = headPtr;


    while ((curPtr != nullptr))
    {

            store = curPtr->getItem();
            tempPtr = curPtr;

        for (int i = 0; i < size; i++)
        {

            if (tempPtr->getNext() != nullptr)
            {
                tempPtr = tempPtr->getNext();
            }

            if (store == tempPtr->getItem())
            {
                remove(store);
            }


        }
        if (curPtr->getNext() != nullptr)
        {
            curPtr = curPtr->getNext();
        }

    } // end while
    return changeFlag;
}  // end flatten
  • You will need to show more code before we can better help you. At a guess, `remove(store)` will invalidate `curPtr` and the call to `curPtr->getNext` can blow up. Also, it looks like you currently have an infinite loop: at the end of the list, you never advance `curPtr` if its next pointer is null, so the loop will run again on the last element. – Botje Feb 25 '19 at 11:40
  • 1
    A *debugger* would be solid right about now. That for-loop on `size` is pointless, btw. And you should seriously consider what state `remove(store)` leaves your list in , specifically what `tempPtr` is pointing at after it's execution. I'm pretty sure you just deleted the node `tempPtr` points to, meaning the next iteration using `tempPtr->getNext()` is invoking undefined behavior. – WhozCraig Feb 25 '19 at 11:40
  • Also, have you tried stepping through this code in a debugger to see how `curPtr` and `tempPtr` evolve, and how your list structure is modified? – Botje Feb 25 '19 at 11:41
  • Yes I stepped through the debugger and it crashes after the for loop. I am still trying to get the feel of using a list to store data. – Geralt of Rivia Feb 25 '19 at 11:48

0 Answers0