I have an assignment to write a reversing function to reverse a linked doubly linked list with up to n blocks. I am first getting the endpoint from size in a forloop, then i send the tartpoint and endpoint to an outside function to reverse them. that outside function successfully reveresed head and tail, but i am segfaulting while tring to reverse a given size. I need some help on what is going wrong?
reverse function;
/**
* 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;
}
Now the reverse function given sze, it should use the above function;
/**
* 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 outputs some wierd stuff, probably given functions working on the image afterwards are failing;
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.
I need to put this in a reply since I don't know if it's possible to do formatted code in a comment.
That said, you're working way too hard at this:
ListNode * curr = startPoint;
while( curr != NULL)
{
ListNode * temp = curr->next;
curr->next = curr->prev;
curr->prev = temp;
curr = temp;
}
should get you where you want to be.
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.