95
社区成员




递归法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *reverseList ( ListNode *head )
{
ListNode* answer = nullptr;
while(head != nullptr){
answer = new ListNode(head->val,answer);
head = head->next;
}
return answer;
}
};
三个指针法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *reverseList ( ListNode *head )
{
ListNode* first = head;
ListNode* second = nullptr;
while(first != nullptr) {
ListNode* next = first->next;
first->next = second;
second = first;
first = next;
}
return second;
}
};