题目描述
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
样例
/*递归版本*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
auto newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
};
/*迭代版本*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head) return head;
auto p = head,q = p->next;
while(q)
{
auto tmp = q->next;
q->next = p;
p = q,q = tmp;
}
head->next = NULL;
return p;
}
};