题目描述
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
迭代法
a维护前一个结点,b维护后一个节点
if (!head || !head->next) return head;
auto a = head, b = a->next;
while (b)
{
auto c = b->next;
b->next = a;
a = b, b = c;
}
head->next = NULL;
return a;
递归法
if (!head || !head->next) return head;
auto tail = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return tail;