不带温度的链表反向
有没有办法在 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;
}
使用临时变量
Saurabh
Is there any way to reverse linked list without using temp variable in C?
Thanks in advance.
the famous approach:
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;
}
uses temp variable
Saurabh
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请注意,您的
temp
使用实际上生成了两个swap()
调用,并且可以替换为:您可以使用 xor 在没有临时值的情况下进行交换,称为 异或交换。
Note that your
temp
usage is actually generating twoswap()
calls, and can be replaced with:You can swap without temps using xor, it is called xor swap.
在指针上使用XOR-swaps来伪造XOR-linked-list。
实现留给读者作为练习。
Use XOR-swaps on the pointers to fake an XOR-linked-list.
Implementation is left to the reader as an exercise.
递归方法:
调用递归函数:
Recursive approach :
Call for recursive function:
如果有人仍然感兴趣,这里是根本不使用新变量的解决方案,除了在递归调用中传递的变量之外。
这个想法如下:首先我们递归地运行 invert 函数,并实现它,以便当它到达最后一个元素时,它将它分配为当前头的下一个元素(参数
first
)。执行后,我们将得到一个反向列表,但会循环,因此当前的 head.next 将指向反向列表的头部。我们将 head 重新分配给它的下一个元素(反向列表的实际头),我们要做的最后一件事就是打破循环。所以我们调用breakCycle
来递归地完成这项工作!If someone is still interested, here is the solution that uses no new variables at all, except for those passed in recursive call.
The idea is the following: first we run invert function recursively, and implement it so that when it reaches the last element it assigns it as a next element of current head (parameter
first
). After we executed it, we will have a reversed list but cycled, so the current head.next will point at the head of the reversed list. We reassign head to its next element (the actual head of the reversed list), and the last thing we have to do is to break the cycle. So we callbreakCycle
which does the job recursively!