简体   繁体   English

双向链接的反向部分(c ++)

[英]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. 因此, head_tail_是指向DLL开头和结尾的指针。 The actual process of reversing the list should be fairly simple - reverse the prev and next pointer for every ListNode in the sequence. 倒车列表的实际过程应该是相当简单-扭转prevnext指针序列中的每ListNode。

As you can see, I'm attempting to make it so that the second method can reverse any sub-part of the DLL. 如您所见,我正在尝试使其能够使第二种方法可以反转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. 我认为最大的问题是head_没有得到适当的更新,因为在我打印列表时什么都没有。

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. 一个实现在实际输出中显示了“ 9”,但是我可以肯定的是,因为列表的第一部分只是被扔掉了。

You can simplify the problem into three steps : 您可以将问题简化为三个步骤:

  1. Store prev of startpoint and next of endpoint, and make them point to nullptr. 存储起点的上一个和终点的下一个,并使它们指向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. 将反向子列表的开始节点和结束节点与步骤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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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