-1

Hey I have build an implementation of linked list in c++ using List class and inner node struct. everything works fine except removing node from tail function:

void  List::remove_tail()
{
    Node* runPtr= new Node;
    runPtr = this->head;
    while(runPtr->next->next !=nullptr) //this loop is not stopping!
    {
        runPtr = runPtr->next;
    }

    this->tail= runPtr;
    delete runPtr;
}

for some reason the while loop is not stopping. what am I missing?

Thanks for the help!

N.Av
  • 21
  • 1
  • 6

1 Answers1

0
  1. Do not allocate new Node for the runPtr. It's a pointer that should point to an already allocated element in the list. Here you're just leaking memory.
  2. Do not dereference pointer without validating it's not null. runPtr might be null, runPtr->next might be null too. In both cases you'll perform unauthorized memory access and either crash or get garbage.
  3. You have to initialize the head pointer to the first element (or null) before attempting to iterate over the list.
  4. You do not update the next pointer of the element that preceding the tail. After the first deletion this will result in a list that doesn't stop at null.
SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85