简体   繁体   中英

Reversing Portions of a Doubly Linked Linked (c++)

I'm attempting to right a method which reverses a doubly linked list.

template <class T>
void List<T>::reverse() {
  reverse(head_, tail_);
}

template <class T>
void List<T>::reverse(ListNode*& startPoint, ListNode*& endPoint) {
  if(startPoint == NULL || endPoint == NULL) return;

  ListNode* currPoint = *&startPoint;
  ListNode* end = endPoint->next;

  while(currPoint != end ) {
    ListNode* tmp = currPoint->next;
    currPoint->next = currPoint->prev;
    currPoint->prev = tmp;

    if(tmp == end) {
      endPoint = startPoint;
      startPoint = currPoint;
    }

    currPoint = tmp;
  }
}

So, head_ and tail_ are the pointers to the beginning and end of the DLL. The actual process of reversing the list should be fairly simple - reverse the prev and next pointer for every ListNode in the sequence.

As you can see, I'm attempting to make it so that the second method can reverse any sub-part of the DLL. I'll be using the second method in other methods, but for now my only goal is to make it work for reversing the entire list. I think that the biggest issue is that head_ isn't being updated appropriately, since nothing is present in the when I print the list.

When I print my fairly basic test it simply shows:

Expected:   < 9 8 7 6 5 4 3 2 1 0 >
Actual:     < >

One implementation was showing the "9" in the actual output, but I'm fairly certain that was because the first portion of the list was simply being thrown away.

You can simplify the problem into three steps :

  1. Store prev of startpoint and next of endpoint, and make them point to nullptr.
  2. Reverse the sublist using the same approach which is used for a full length of linked list.
  3. Connect start and end nodes of reversed sublist with the stored values in step 1.

This way

[prev] startpoint  ... endpoint [nxt]

[prev]   (nullptr) startpoint... endpoint (nullptr)   [nxt]

[prev]   (nullptr) reverse(startpoint...endpoint) (nullptr)   [nxt]

[prev] begin(reversed-sublist) ...end(reversed-sublist)  [nxt]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM