题目:
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
struct listNode {
int m_nValue;
listNode* m_pNext;
};
解法:
listNode* reverse_recursive(listNode* head) {
if (head == 0 || head->m_pNext == 0) return head;
listNode* p = head;
listNode* h = reverse_recursive(head->m_pNext);
listNode* tmp = h;
while (tmp->m_pNext) {
tmp = tmp->m_pNext;
}
tmp->m_pNext = p;
p->m_pNext = 0;
return h;
}