链表反转还是很绕的,对于C++,则纯粹是在玩弄指针,弄清指针和内存的关系很重要。在左侧的是指针,在右侧的是内存。
template <typename T> struct ListStack; template <typename T> struct Node { private: T item; Node *next = nullptr; friend class ListStack<T>; } template <typename T> struct ListStack { void reverse() { Node<T> *reverse = nullptr; Node<T> *second = nullptr; while (first) { second = first->next; first->next = reverse; reverse = first; first = second; } first = reverse; } private: Node<T> *first = nullptr; unsigned N = 0; };