c - 反向双链表

标签 c list pointers linked-list reverse

我必须编写一个函数来反转双链表,使尾部变成头部。

例如前面的元素: {(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;
  };

这是我必须使用的函数原型(prototype):

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;
    }
}

关于c - 反向双链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42256344/

相关文章:

c - 在C中有什么区别?

将 C char 数组转换为 Matlab 字符串 [Matlab Coder]

c - 使用strcpy时出现段错误?

Python 重新组合字典中的项目

c++ - 如何在 C++ 中使用指针翻转 Char 数组

C 通过指针将数组传递给函数

c - KAA 无法创建 kaa_configuration_manager_set_root_receiver

c - NVCC:警告:允许所有异常与以前的功能不兼容

python - 如何将 JSON 字符串转换为 Python 数据结构

c# - 为什么List.Add即使存在对象也返回错误 'Object reference not set to an instance of an object'?