0
//This function reverses part of a doubly linked list, and modify the startPoint
//and endPoint pointers to the new start and end.    
void List<T>::reverse(ListNode *& startPoint, ListNode *& endPoint) {
    if((startPoint==NULL)||(endPoint==NULL)||(startPoint==endPoint)) return;
    ListNode* tmp=NULL;
    ListNode* crr=startPoint;
    ListNode* endNext=endPoint->next;
    ListNode* startPrev=startPoint->prev;
    while(crr!=endNext){
        tmp=crr->prev;
        crr->prev=crr->next;
        crr->next=tmp;

        crr=crr->prev;
    }
    if(startPrev!=NULL) startPrev->next=endPoint;
    //problem happens after this line
    if(endNext!=NULL) endNext->prev=startPoint;

    tmp=startPoint->next;
    startPoint->next=endPoint->prev;;
    endPoint->prev=tmp;

    tmp=startPoint;
    startPoint=endPoint;
    endPoint=tmp;
}

After I ran this in GDB, I found that when I was doing "startPrev->next=endPoint", it actually changed the startPointer. But I only want to change the next pointer. It seems that the next pointer acted as if it is a reference to startPointer, which should not happen. What is wrong with my code?

Breakpoint 2, List<int>::reverse (this=0x7ffffffee180, startPoint=@0x623260: 0x6232c0,
    endPoint=@0x7ffffffee188: 0x6232e0) at ./List.hpp:126
126             while(crr!=endNext){
(gdb) next
133             if(startPrev!=NULL) startPrev->next=endPoint;
(gdb) info args
this = 0x7ffffffee180
startPoint = @0x623260: 0x6232c0
endPoint = @0x7ffffffee188: 0x6232e0
(gdb) info locals
tmp = 0x6232c0
crr = 0x0
endNext = 0x0
startPrev = 0x623260
(gdb) next
134             if(endNext!=NULL) endNext->prev=startPoint;
(gdb) info locals
tmp = 0x6232c0
crr = 0x0
endNext = 0x0
startPrev = 0x623260
(gdb) info args
this = 0x7ffffffee180
startPoint = @0x623260: 0x6232e0
endPoint = @0x7ffffffee188: 0x6232e0
  • 2
    Use pen and paper and draw all your nodes and pointers. It's the best way to work with pointer structures. – molbdnilo Sep 27 '18 at 04:57
  • Also look into seeing if you can adapt [this trick with a pointer to a pointer](https://stackoverflow.com/a/52527298/4581301) to help you reduce the amount of book-keeping you have to maintain. – user4581301 Sep 27 '18 at 05:06

0 Answers0