题目:
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
思考题:
请同时实现迭代版本和递归版本。
代码实现:
//迭代解法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
while(cur){
ListNode* next = cur->next;//防止断链
cur->next = pre;
pre = cur,cur = next;
}
return pre;
}
};
//递归解法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* tail = reverseList(head->next);
head->next->next = head;
head ->next = nullptr;
return tail;
}
};