可能重复:
反转单链表
如何在单个 for 循环中反转单链表?这是在一次采访中被问到的问题。
在伪代码中,这看起来像:
// Cache the start element
current = first;
next = current->next;
while (next != null) {
// Cache the next pointer to not lose the reference
temp = next->next;
next->next = current;
// Increment
current = next;
next = temp;
}
first = current;
我知道它不在 for 循环中,但可以很容易地重写为。随着时间的推移,它使它更具可读性。