有没有办法在 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/