while (p != nullptr) { stk.push(p); p = p->next; }
head = stk.top(); ListNode *last = head; stk.pop();
while (!stk.empty()) { p = stk.top(); stk.pop(); last->next = p; last = p; } last->next = nullptr;
return head; } };
After reading the solution, it can also be done with O(1) space complexity.
Assume the linked list is 1→2→3→∅, we want to change it to ∅←1←2←3.
When traversing the linked list, change the current node’s next pointer to point to the previous node. Since the node does not reference its previous node, you must store its previous node beforehand. Before changing the reference, you also need to store the next node. Finally, return the new head reference.