Domanda di colloquio di SingleStore

Reverse a linked list using recursion and otherwise.

Risposta di colloquio

Anonimo

19 feb 2017

The idea is that you recurs to the last node and keep the pre pointer at the same time. When you reach the last node change the current next pointer to the pre. ListNode* reverse (ListNode* head) { ListNode* p = head; return travel(p, nullptr, head); } ListNode* travel(ListNode* p, ListNode* pre) { (p->next == nullptr) { p->next = pre; return p; } ListNode* re = travel(p->next, p); p->next = pre; return re; }