[英]Reverse double linked list
我必须编写一个函数来反转双链表,以便尾部成为头部。
例如,之前的元素:{(1,1),(1,2),(2,2),(2,3)}
之后:{(2,3),(2,2),(1,2),(1,1)}
结构如下:
struct snake {
unsigned int i;
unsigned int j;
struct snake *next;
struct snake *prev;
};
这是我必须使用的函数原型:
void snake_reverse(struct snake **s);
我尝试了这样的尝试和其他几次尝试
void snake_reverse(struct snake **s) {
struct snake *last, *tmp = NULL;
last = *s;
while (last != NULL)
{
tmp = last->prev;
last->prev = last->next;
last->next = tmp;
last = last->prev;
}
if(tmp != NULL )
*s = tmp->prev;
}
还尝试了以下方法:
while (last != NULL)
{
tmp = last->next;
last->next = last->prev;
last->prev = tmp;
last = tmp;
}
if(tmp != NULL )
*s = tmp;
但他不工作。 我几乎可以确定我没有记错。 列表的第一个-> prev为NULL,列表的最后一个-> next为NULL。
我没有遇到任何错误或崩溃,但是该函数的任务是通过反转所有元素并更改列表的开头来反转蛇的方向。 你能说出什么问题吗?
编辑:问题出在不是我的程序的另一个模块中。
无论如何,最好的解决方案是kmkaplan。 谢谢大家
您必须将*s
设置为列表的新标题。 那是列表的旧尾,是您处理的最后一个元素。
void snake_reverse(struct snake **s) {
struct snake *last, *tmp = NULL;
last = *s;
while (last != NULL) {
*s = last
tmp = last->prev;
last->prev = last->next;
last->next = tmp;
last = last->prev;
}
}
我不确定,但是我认为while循环中的最后一行代码是错误的。 据我了解,最后一个变量是蛇的尾巴。 这意味着last-> next = null。 在您的while的第二行代码中,使last的前一个为null,在while的最后一行代码中,last变为0。我认为,在while循环中更改最后的代码行将对此进行更改。
last = last->next
您永远不会设置列表的新标题,因为while循环之后tmp始终为NULL。 尝试这个;
void snake_reverse(struct snake **s) {
struct snake *last, *newHead, *tmp = NULL;
last = *s;
while (last != NULL)
{
tmp = last->prev;
if (tmp!=NULL)
newHead = tmp;
last->prev = last->next;
last->next = tmp;
last = last->prev;
}
*s = newHead;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.