Sau*_*ade 7 c linked-list data-structures
有没有办法在不使用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;
}
Run Code Online (Sandbox Code Playgroud)
使用临时变量
SAURABH
请注意,您的temp使用实际上是生成两个swap()调用,可以替换为:
swap(head->next,previous);
swap(previous,head);
Run Code Online (Sandbox Code Playgroud)
你可以使用xor交换不带temps,它叫做xor swap.