给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
迭代法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* first = nullptr;
ListNode* second = head;
while (second != nullptr) {
ListNode* nextNode = second -> next;
second -> next = first;
first = second;
second = nextNode;
}
return first;
}
};
递归法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr || head -> next==nullptr) {
return head;
}
ListNode* result = reverseList(head -> next);
head -> next -> next = head;
head -> next = nullptr;
return result;
}
};