1、正常逻辑来写,迭代法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
if (head == nullptr || head->next == nullptr)
return head;
ListNode* temp = head;
ListNode* next_head = head->next;
while (next_head != nullptr)
{
ListNode* node = head;
head = next_head;
next_head = head->next;
head->next = node;
}
temp->next = nullptr;
return head;
}
};
2、递归法
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
if (head == nullptr || head->next == nullptr)
return head;
ListNode* newHead = reverseList(head->next);
head->next->next = head;//注意该处不要用newHead->next = head
head->next = nullptr;
return newHead;
}
};