c - 没有温度的链表反向

标签 c data-structures linked-list

有没有办法在 C 中不使用临时变量来反转链表? 提前致谢。

著名的方法:

Element *reverse(Element *head)
{
    Element *previous = NULL;

    while (head != NULL) {
        // Keep next node since we trash
        // the next pointer.
        Element *next = head->next;

        // Switch the next pointer
        // to point backwards.
        head->next = previous;

        // Move both pointers forward.
        previous = head;
        head = next;
    }

    return previous;
}

使用临时变量

苏拉布

最佳答案

请注意,您的 temp 用法实际上生成了两个 swap() 调用,可以替换为:

swap(head->next,previous);
swap(previous,head);

您可以使用 xor 进行无临时交换,称为 xor swap .

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

相关文章:

c - 静态库中定义的 IRQ 符号不会覆盖 ARM/GCC 启动时的弱 IRQ 定义

c++ - 排序数据结构通过迭代器快速迭代、插入、删除

java - 保存时间戳对象列表的数据结构

java - 这怎么不是 Java 可见性违规

C 数据类型从 stdin 读取不同的输入并打印更改的数据

c - 使用 autotools 链接 gstreamer 插件中的外部库

c - 错误 : 'type name' declared as function returning a function

ajax - 基于 DOM 的数据存储,最佳选择/性能?

c - 通过函数传递时指向 NULL 的全局链表

C++:简单节点/链表