使用给定大小反转链接列表时的Segfault

时间:2014-09-28 20:44:01

标签: c++ function pointers linked-list segmentation-fault

我有一个编写反转函数的赋值,用于反转最多n个块的链接双向链表。我首先从forloop中获取大小的端点,然后我将tartpoint和端点发送到外部函数以反转它们。外部功能成功地尊重了头部和尾部,但是我正在进行分裂,同时扭转一个给定的大小。我需要帮助解决出错的问题?

反向功能;

/**
 * Helper function to reverse a sequence of linked memory inside a List,
 * starting at startPoint and ending at endPoint. You are responsible for
 * updating startPoint and endPoint to point to the new starting and ending
 * points of the rearranged sequence of linked memory in question.
 *
 * @param startPoint A pointer reference to the first node in the sequence
 *  to be reversed. 
 * @param endPoint A pointer reference to the last node in the sequence to
 *  be reversed.
 */
template <class T>
void List<T>::reverse( ListNode * & startPoint, ListNode * & endPoint )
{
    if( (startPoint == NULL) || (endPoint == NULL) || (startPoint == endPoint))
    {    return;     }                                                                
    ListNode * curr = startPoint;
    ListNode * nexter = NULL;
    ListNode * prever = endPoint->next;             
    while( curr != NULL)
    { 
       nexter = curr->next;
       curr->next = prever;
       prever = curr;
       curr = nexter;
      prever->prev = curr;
  }

  // now swap start and end pts
   nexter = startPoint;
   startPoint = endPoint;
   endPoint = nexter;

}

现在给出sze的反向函数,它应该使用上面的函数;

/**
* Reverses blocks of size n in the current List. You should use your
* reverse( ListNode * &, ListNode * & ) helper function in this method!
*
* @param n The size of the blocks in the List to be reversed.
*/
template <class T>
void List<T>::reverseNth( int n )
 {
 if(n == 0)
   return;

  ListNode * startPoint = head;
  ListNode * endPoint = head;
  ListNode * save = NULL;

  for(int i = 0; i< n; i++)                           // need to get endpoint at n
  {
      endPoint = endPoint->next;

   }    
 reverse(startPoint, endPoint);

}

gdb会输出一些奇怪的东西,可能是因为在图像上工作的函数失败了;

 Program received signal SIGINT, Interrupt.
 0x000000000040dcab in __distance<List<RGBAPixel>::ListIterator> (__first=..., __last=...) at      /class/cs225/llvm/include/c++/v1/iterator:488
 488        for (; __first != __last; ++__first)
(gdb) q
A debugging session is active.

 Inferior 1 [process 31022] will be killed.

1 个答案:

答案 0 :(得分:1)

我需要回复此问题,因为我不知道是否可以在评论中执行格式化代码。

那就是说,你在这方面的工作太过努力了:

ListNode * curr = startPoint;
while( curr != NULL)
{
    ListNode * temp = curr->next;
    curr->next = curr->prev;
    curr->prev = temp;
    curr = temp;
}

应该让你到达你想去的地方。