在反转具有给定大小的链接列表时发生Segfault
Segfault while reversing a link list with a give size
我有一个任务要写一个反转函数来反转一个最多有n个块的双链表。我首先从forloop中的大小获取端点,然后将起点和端点发送到外部函数以反转它们。这个外部函数成功地反转了头部和尾部,但我在尝试反转给定大小时正在分段。我需要一些帮助,看看出了什么问题?
逆向函数;
/**
* 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输出一些wierd的东西,可能是因为之后处理图像的函数失败了;
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.
我需要把它放在回复中,因为我不知道是否可以在注释中执行格式化代码。
也就是说,你在这方面太努力了:
ListNode * curr = startPoint;
while( curr != NULL)
{
ListNode * temp = curr->next;
curr->next = curr->prev;
curr->prev = temp;
curr = temp;
}
应该会让你到达你想要的地方。
相关文章:
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表