我有一個任務來寫一個反轉函數來反轉鏈接雙向鏈表,最多n個塊。我首先從forloop中獲取端點的大小,然後我將tartpoint和端點發送到外部函數以反轉它們。外部功能成功地恢復了頭部和尾部,但是我在劃轉時扭轉了給定的尺寸。我需要一些幫助解決問題?Segvert同時反轉給定大小的鏈接列表
反轉功能;
/**
* 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;
}
現在給定事反向功能,它應該使用上述功能;
/**
* 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.
'endPoint = endPoint-> next;'如果你打到列表的末尾,你將最終取消引用一個空指針。 – 2014-09-28 20:49:11
您是否試圖回溯('bt')? – SHR 2014-09-28 21:08:29
我放了一會兒(endpoint->!= NULL),但程序仍然處於無限循環。回溯帶我到其他功能,我們不應該touchof – user124627 2014-09-28 22:18:54